blob: 6f076e27b72bf78bb91c6aacb4090ad0cbdf341d [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000016#include "llvm/AutoUpgrade.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000017#include "llvm/IR/CallingConv.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/InlineAsm.h"
21#include "llvm/IR/Instructions.h"
22#include "llvm/IR/Module.h"
23#include "llvm/IR/Operator.h"
24#include "llvm/IR/ValueSymbolTable.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000025#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000026#include "llvm/Support/raw_ostream.h"
27using namespace llvm;
28
Chris Lattnerdb125cf2011-07-18 04:54:35 +000029static std::string getTypeString(Type *T) {
Chris Lattner0cd0d882011-06-18 21:18:23 +000030 std::string Result;
31 raw_string_ostream Tmp(Result);
32 Tmp << *T;
33 return Tmp.str();
34}
35
Chris Lattner3ed88ef2009-01-02 08:05:26 +000036/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000037bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000038 // Prime the lexer.
39 Lex.Lex();
40
Chris Lattnerad7d1e22009-01-04 20:44:11 +000041 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000043}
44
45/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
46/// module.
47bool LLParser::ValidateEndOfModule() {
Chris Lattner449c3102010-04-01 05:14:45 +000048 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
52 I != E; ++I) {
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
Michael Ilseman407a6162012-11-15 22:34:00 +000055
Chris Lattner449c3102010-04-01 05:14:45 +000056 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
Michael Ilseman407a6162012-11-15 22:34:00 +000058
Chris Lattner449c3102010-04-01 05:14:45 +000059 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +000061 Twine(SlotNo) + "'");
Chris Lattner449c3102010-04-01 05:14:45 +000062 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
63 }
64 }
65 ForwardRefInstMetadata.clear();
66 }
Michael Ilseman407a6162012-11-15 22:34:00 +000067
Bill Wendlingbaad55c2013-02-08 06:32:06 +000068 // Handle any function attribute group forward references.
69 for (std::map<Value*, std::vector<unsigned> >::iterator
70 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
71 I != E; ++I) {
72 Value *V = I->first;
73 std::vector<unsigned> &Vec = I->second;
74 AttrBuilder B;
75
76 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
77 VI != VE; ++VI)
78 B.merge(NumberedAttrBuilders[*VI]);
79
80 if (Function *Fn = dyn_cast<Function>(V)) {
81 AttributeSet AS = Fn->getAttributes();
82 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
83 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
84 AS.getFnAttributes());
85
86 FnAttrs.merge(B);
87
88 // If the alignment was parsed as an attribute, move to the alignment
89 // field.
90 if (FnAttrs.hasAlignmentAttr()) {
91 Fn->setAlignment(FnAttrs.getAlignment());
92 FnAttrs.removeAttribute(Attribute::Alignment);
93 }
94
95 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
96 AttributeSet::get(Context,
97 AttributeSet::FunctionIndex,
98 FnAttrs));
99 Fn->setAttributes(AS);
100 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
101 AttributeSet AS = CI->getAttributes();
102 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
103 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
104 AS.getFnAttributes());
105
106 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
107 AttributeSet::get(Context,
108 AttributeSet::FunctionIndex,
109 FnAttrs));
110 CI->setAttributes(AS);
111 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
112 AttributeSet AS = II->getAttributes();
113 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
114 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
115 AS.getFnAttributes());
116
117 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
118 AttributeSet::get(Context,
119 AttributeSet::FunctionIndex,
120 FnAttrs));
121 II->setAttributes(AS);
122 } else {
123 llvm_unreachable("invalid object with forward attribute group reference");
124 }
125 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000126
Chris Lattner09d9ef42009-10-28 03:39:23 +0000127 // If there are entries in ForwardRefBlockAddresses at this point, they are
128 // references after the function was defined. Resolve those now.
129 while (!ForwardRefBlockAddresses.empty()) {
130 // Okay, we are referencing an already-parsed function, resolve them now.
131 Function *TheFn = 0;
132 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
133 if (Fn.Kind == ValID::t_GlobalName)
134 TheFn = M->getFunction(Fn.StrVal);
135 else if (Fn.UIntVal < NumberedVals.size())
136 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
Michael Ilseman407a6162012-11-15 22:34:00 +0000137
Chris Lattner09d9ef42009-10-28 03:39:23 +0000138 if (TheFn == 0)
139 return Error(Fn.Loc, "unknown function referenced by blockaddress");
Michael Ilseman407a6162012-11-15 22:34:00 +0000140
Chris Lattner09d9ef42009-10-28 03:39:23 +0000141 // Resolve all these references.
Michael Ilseman407a6162012-11-15 22:34:00 +0000142 if (ResolveForwardRefBlockAddresses(TheFn,
Chris Lattner09d9ef42009-10-28 03:39:23 +0000143 ForwardRefBlockAddresses.begin()->second,
144 0))
145 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000146
Chris Lattner09d9ef42009-10-28 03:39:23 +0000147 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
148 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000149
Chris Lattner1afcace2011-07-09 17:41:24 +0000150 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
151 if (NumberedTypes[i].second.isValid())
152 return Error(NumberedTypes[i].second,
153 "use of undefined type '%" + Twine(i) + "'");
154
155 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
156 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
157 if (I->second.second.isValid())
158 return Error(I->second.second,
159 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000160
Chris Lattnerdf986172009-01-02 07:01:27 +0000161 if (!ForwardRefVals.empty())
162 return Error(ForwardRefVals.begin()->second.second,
163 "use of undefined value '@" + ForwardRefVals.begin()->first +
164 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000165
Chris Lattnerdf986172009-01-02 07:01:27 +0000166 if (!ForwardRefValIDs.empty())
167 return Error(ForwardRefValIDs.begin()->second.second,
168 "use of undefined value '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000169 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000170
Devang Patel1c7eea62009-07-08 19:23:54 +0000171 if (!ForwardRefMDNodes.empty())
172 return Error(ForwardRefMDNodes.begin()->second.second,
173 "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000174 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000175
Devang Patel1c7eea62009-07-08 19:23:54 +0000176
Chris Lattnerdf986172009-01-02 07:01:27 +0000177 // Look for intrinsic functions and CallInst that need to be upgraded
178 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
179 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000180
Chris Lattnerdf986172009-01-02 07:01:27 +0000181 return false;
182}
183
Michael Ilseman407a6162012-11-15 22:34:00 +0000184bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
Chris Lattner09d9ef42009-10-28 03:39:23 +0000185 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
186 PerFunctionState *PFS) {
187 // Loop over all the references, resolving them.
188 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
189 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000190 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000191 if (Refs[i].first.Kind == ValID::t_LocalName)
192 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000193 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000194 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
195 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
196 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000197 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000198 } else {
199 Res = dyn_cast_or_null<BasicBlock>(
200 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
201 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000202
Chris Lattnercdfc9402009-11-01 01:27:45 +0000203 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000204 return Error(Refs[i].first.Loc,
205 "referenced value is not a basic block");
Michael Ilseman407a6162012-11-15 22:34:00 +0000206
Chris Lattner09d9ef42009-10-28 03:39:23 +0000207 // Get the BlockAddress for this and update references to use it.
208 BlockAddress *BA = BlockAddress::get(TheFn, Res);
209 Refs[i].second->replaceAllUsesWith(BA);
210 Refs[i].second->eraseFromParent();
211 }
212 return false;
213}
214
215
Chris Lattnerdf986172009-01-02 07:01:27 +0000216//===----------------------------------------------------------------------===//
217// Top-Level Entities
218//===----------------------------------------------------------------------===//
219
220bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000221 while (1) {
222 switch (Lex.getKind()) {
223 default: return TokError("expected top-level entity");
224 case lltok::Eof: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000225 case lltok::kw_declare: if (ParseDeclare()) return true; break;
226 case lltok::kw_define: if (ParseDefine()) return true; break;
227 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
228 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling3defc0b2012-11-28 08:41:48 +0000229 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000230 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000231 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000232 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000233 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000234 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling95ce4c22013-02-06 06:52:58 +0000235 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
236 case lltok::AttrGrpID: if (ParseUnnamedAttrGrp()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000237
238 // The Global variable production with no name can have many different
239 // optional leading prefixes, the production is:
240 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000241 // OptionalAddrSpace OptionalUnNammedAddr
242 // ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000243 case lltok::kw_private: // OptionalLinkage
244 case lltok::kw_linker_private: // OptionalLinkage
245 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling32811be2012-08-17 18:33:14 +0000246 case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat.
Bill Wendling5e721d72010-07-01 21:55:59 +0000247 case lltok::kw_internal: // OptionalLinkage
248 case lltok::kw_weak: // OptionalLinkage
249 case lltok::kw_weak_odr: // OptionalLinkage
250 case lltok::kw_linkonce: // OptionalLinkage
251 case lltok::kw_linkonce_odr: // OptionalLinkage
Bill Wendling32811be2012-08-17 18:33:14 +0000252 case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000253 case lltok::kw_appending: // OptionalLinkage
254 case lltok::kw_dllexport: // OptionalLinkage
255 case lltok::kw_common: // OptionalLinkage
256 case lltok::kw_dllimport: // OptionalLinkage
257 case lltok::kw_extern_weak: // OptionalLinkage
258 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000259 unsigned Linkage, Visibility;
260 if (ParseOptionalLinkage(Linkage) ||
261 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000262 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000263 return true;
264 break;
265 }
266 case lltok::kw_default: // OptionalVisibility
267 case lltok::kw_hidden: // OptionalVisibility
268 case lltok::kw_protected: { // OptionalVisibility
269 unsigned Visibility;
270 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000271 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000272 return true;
273 break;
274 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000275
Chris Lattnerdf986172009-01-02 07:01:27 +0000276 case lltok::kw_thread_local: // OptionalThreadLocal
277 case lltok::kw_addrspace: // OptionalAddrSpace
278 case lltok::kw_constant: // GlobalType
279 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000280 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000281 break;
282 }
283 }
284}
285
286
287/// toplevelentity
288/// ::= 'module' 'asm' STRINGCONSTANT
289bool LLParser::ParseModuleAsm() {
290 assert(Lex.getKind() == lltok::kw_module);
291 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000292
293 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000294 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
295 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000296
Rafael Espindola38c4e532011-03-02 04:14:42 +0000297 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000298 return false;
299}
300
301/// toplevelentity
302/// ::= 'target' 'triple' '=' STRINGCONSTANT
303/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
304bool LLParser::ParseTargetDefinition() {
305 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000306 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000307 switch (Lex.Lex()) {
308 default: return TokError("unknown target property");
309 case lltok::kw_triple:
310 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000311 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
312 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000313 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000314 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000315 return false;
316 case lltok::kw_datalayout:
317 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000318 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
319 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000320 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000321 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000322 return false;
323 }
324}
325
Bill Wendling3defc0b2012-11-28 08:41:48 +0000326/// toplevelentity
327/// ::= 'deplibs' '=' '[' ']'
328/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
329/// FIXME: Remove in 4.0. Currently parse, but ignore.
330bool LLParser::ParseDepLibs() {
331 assert(Lex.getKind() == lltok::kw_deplibs);
332 Lex.Lex();
333 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
334 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
335 return true;
336
337 if (EatIfPresent(lltok::rsquare))
338 return false;
339
340 do {
341 std::string Str;
342 if (ParseStringConstant(Str)) return true;
343 } while (EatIfPresent(lltok::comma));
344
345 return ParseToken(lltok::rsquare, "expected ']' at end of list");
346}
347
Dan Gohman3845e502009-08-12 23:32:33 +0000348/// ParseUnnamedType:
Dan Gohman3845e502009-08-12 23:32:33 +0000349/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000350bool LLParser::ParseUnnamedType() {
Chris Lattneredcaca82011-06-18 23:51:31 +0000351 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +0000352 unsigned TypeID = Lex.getUIntVal();
Chris Lattnera53616d2011-06-19 00:03:46 +0000353 Lex.Lex(); // eat LocalVarID;
354
355 if (ParseToken(lltok::equal, "expected '=' after name") ||
356 ParseToken(lltok::kw_type, "expected 'type' after '='"))
357 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000358
Chris Lattner1afcace2011-07-09 17:41:24 +0000359 if (TypeID >= NumberedTypes.size())
360 NumberedTypes.resize(TypeID+1);
Michael Ilseman407a6162012-11-15 22:34:00 +0000361
Chris Lattner1afcace2011-07-09 17:41:24 +0000362 Type *Result = 0;
363 if (ParseStructDefinition(TypeLoc, "",
364 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000365
Chris Lattner1afcace2011-07-09 17:41:24 +0000366 if (!isa<StructType>(Result)) {
367 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
368 if (Entry.first)
369 return Error(TypeLoc, "non-struct types may not be recursive");
370 Entry.first = Result;
371 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000372 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000373
Chris Lattnerdf986172009-01-02 07:01:27 +0000374 return false;
375}
376
Chris Lattner1afcace2011-07-09 17:41:24 +0000377
Chris Lattnerdf986172009-01-02 07:01:27 +0000378/// toplevelentity
379/// ::= LocalVar '=' 'type' type
380bool LLParser::ParseNamedType() {
381 std::string Name = Lex.getStrVal();
382 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000383 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000384
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000385 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000386 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000387 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000388
Chris Lattner1afcace2011-07-09 17:41:24 +0000389 Type *Result = 0;
390 if (ParseStructDefinition(NameLoc, Name,
391 NamedTypes[Name], Result)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000392
Chris Lattner1afcace2011-07-09 17:41:24 +0000393 if (!isa<StructType>(Result)) {
394 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
395 if (Entry.first)
396 return Error(NameLoc, "non-struct types may not be recursive");
397 Entry.first = Result;
398 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000399 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000400
Chris Lattner1afcace2011-07-09 17:41:24 +0000401 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000402}
403
404
405/// toplevelentity
406/// ::= 'declare' FunctionHeader
407bool LLParser::ParseDeclare() {
408 assert(Lex.getKind() == lltok::kw_declare);
409 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000410
Chris Lattnerdf986172009-01-02 07:01:27 +0000411 Function *F;
412 return ParseFunctionHeader(F, false);
413}
414
415/// toplevelentity
416/// ::= 'define' FunctionHeader '{' ...
417bool LLParser::ParseDefine() {
418 assert(Lex.getKind() == lltok::kw_define);
419 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000420
Chris Lattnerdf986172009-01-02 07:01:27 +0000421 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000422 return ParseFunctionHeader(F, true) ||
423 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000424}
425
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000426/// ParseGlobalType
427/// ::= 'constant'
428/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000429bool LLParser::ParseGlobalType(bool &IsConstant) {
430 if (Lex.getKind() == lltok::kw_constant)
431 IsConstant = true;
432 else if (Lex.getKind() == lltok::kw_global)
433 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000434 else {
435 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000436 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000437 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000438 Lex.Lex();
439 return false;
440}
441
Dan Gohman3845e502009-08-12 23:32:33 +0000442/// ParseUnnamedGlobal:
443/// OptionalVisibility ALIAS ...
444/// OptionalLinkage OptionalVisibility ... -> global variable
445/// GlobalID '=' OptionalVisibility ALIAS ...
446/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
447bool LLParser::ParseUnnamedGlobal() {
448 unsigned VarID = NumberedVals.size();
449 std::string Name;
450 LocTy NameLoc = Lex.getLoc();
451
452 // Handle the GlobalID form.
453 if (Lex.getKind() == lltok::GlobalID) {
454 if (Lex.getUIntVal() != VarID)
455 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000456 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000457 Lex.Lex(); // eat GlobalID;
458
459 if (ParseToken(lltok::equal, "expected '=' after name"))
460 return true;
461 }
462
463 bool HasLinkage;
464 unsigned Linkage, Visibility;
465 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
466 ParseOptionalVisibility(Visibility))
467 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000468
Dan Gohman3845e502009-08-12 23:32:33 +0000469 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
470 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
471 return ParseAlias(Name, NameLoc, Visibility);
472}
473
Chris Lattnerdf986172009-01-02 07:01:27 +0000474/// ParseNamedGlobal:
475/// GlobalVar '=' OptionalVisibility ALIAS ...
476/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
477bool LLParser::ParseNamedGlobal() {
478 assert(Lex.getKind() == lltok::GlobalVar);
479 LocTy NameLoc = Lex.getLoc();
480 std::string Name = Lex.getStrVal();
481 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000482
Chris Lattnerdf986172009-01-02 07:01:27 +0000483 bool HasLinkage;
484 unsigned Linkage, Visibility;
485 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
486 ParseOptionalLinkage(Linkage, HasLinkage) ||
487 ParseOptionalVisibility(Visibility))
488 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000489
Chris Lattnerdf986172009-01-02 07:01:27 +0000490 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
491 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
492 return ParseAlias(Name, NameLoc, Visibility);
493}
494
Devang Patel256be962009-07-20 19:00:08 +0000495// MDString:
496// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000497bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000498 std::string Str;
499 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000500 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000501 return false;
502}
503
504// MDNode:
505// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000506//
507/// This version of ParseMDNodeID returns the slot number and null in the case
508/// of a forward reference.
509bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
510 // !{ ..., !42, ... }
511 if (ParseUInt32(SlotNo)) return true;
512
513 // Check existing MDNode.
514 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
515 Result = NumberedMetadata[SlotNo];
516 else
517 Result = 0;
518 return false;
519}
520
Chris Lattner4a72efc2009-12-30 04:15:23 +0000521bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000522 // !{ ..., !42, ... }
523 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000524 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000525
Chris Lattner449c3102010-04-01 05:14:45 +0000526 // If not a forward reference, just return it now.
527 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000528
Chris Lattner449c3102010-04-01 05:14:45 +0000529 // Otherwise, create MDNode forward reference.
Jay Foadec9186b2011-04-21 19:59:31 +0000530 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Patel256be962009-07-20 19:00:08 +0000531 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Michael Ilseman407a6162012-11-15 22:34:00 +0000532
Chris Lattner0834e6a2009-12-30 04:51:58 +0000533 if (NumberedMetadata.size() <= MID)
534 NumberedMetadata.resize(MID+1);
535 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000536 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000537 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000538}
Devang Patel256be962009-07-20 19:00:08 +0000539
Chris Lattner84d03b12009-12-29 22:35:39 +0000540/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000541/// !foo = !{ !1, !2 }
542bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000543 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000544 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000545 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000546
Chris Lattner84d03b12009-12-29 22:35:39 +0000547 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000548 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000549 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000550 return true;
551
Dan Gohman17aa92c2010-07-21 23:38:33 +0000552 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000553 if (Lex.getKind() != lltok::rbrace)
554 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000555 if (ParseToken(lltok::exclaim, "Expected '!' here"))
556 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000557
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000558 MDNode *N = 0;
559 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000560 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000561 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000562
563 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
564 return true;
565
Devang Pateleff2ab62009-07-29 00:34:02 +0000566 return false;
567}
568
Devang Patel923078c2009-07-01 19:21:12 +0000569/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000570/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000571bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000572 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000573 Lex.Lex();
574 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000575
576 LocTy TyLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +0000577 Type *Ty = 0;
Devang Patel104cf9e2009-07-23 01:07:34 +0000578 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000579 if (ParseUInt32(MetadataID) ||
580 ParseToken(lltok::equal, "expected '=' here") ||
581 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000582 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000583 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000584 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000585 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000586 return true;
587
Jay Foadec9186b2011-04-21 19:59:31 +0000588 MDNode *Init = MDNode::get(Context, Elts);
Michael Ilseman407a6162012-11-15 22:34:00 +0000589
Chris Lattner0834e6a2009-12-30 04:51:58 +0000590 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000591 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000592 FI = ForwardRefMDNodes.find(MetadataID);
593 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000594 MDNode *Temp = FI->second.first;
595 Temp->replaceAllUsesWith(Init);
596 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000597 ForwardRefMDNodes.erase(FI);
Michael Ilseman407a6162012-11-15 22:34:00 +0000598
Chris Lattner0834e6a2009-12-30 04:51:58 +0000599 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
600 } else {
601 if (MetadataID >= NumberedMetadata.size())
602 NumberedMetadata.resize(MetadataID+1);
603
604 if (NumberedMetadata[MetadataID] != 0)
605 return TokError("Metadata id is already used");
606 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000607 }
608
Devang Patel923078c2009-07-01 19:21:12 +0000609 return false;
610}
611
Chris Lattnerdf986172009-01-02 07:01:27 +0000612/// ParseAlias:
613/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
614/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000615/// ::= TypeAndValue
616/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000617/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000618///
619/// Everything through visibility has already been parsed.
620///
621bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
622 unsigned Visibility) {
623 assert(Lex.getKind() == lltok::kw_alias);
624 Lex.Lex();
625 unsigned Linkage;
626 LocTy LinkageLoc = Lex.getLoc();
627 if (ParseOptionalLinkage(Linkage))
628 return true;
629
630 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000631 Linkage != GlobalValue::WeakAnyLinkage &&
632 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000633 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000634 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000635 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling32811be2012-08-17 18:33:14 +0000636 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000637 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000638
Chris Lattnerdf986172009-01-02 07:01:27 +0000639 Constant *Aliasee;
640 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000641 if (Lex.getKind() != lltok::kw_bitcast &&
642 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000643 if (ParseGlobalTypeAndValue(Aliasee)) return true;
644 } else {
645 // The bitcast dest type is not present, it is implied by the dest type.
646 ValID ID;
647 if (ParseValID(ID)) return true;
648 if (ID.Kind != ValID::t_Constant)
649 return Error(AliaseeLoc, "invalid aliasee");
650 Aliasee = ID.ConstantVal;
651 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000652
Duncan Sands1df98592010-02-16 11:11:14 +0000653 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000654 return Error(AliaseeLoc, "alias must have pointer type");
655
656 // Okay, create the alias but do not insert it into the module yet.
657 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
658 (GlobalValue::LinkageTypes)Linkage, Name,
659 Aliasee);
660 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000661
Chris Lattnerdf986172009-01-02 07:01:27 +0000662 // See if this value already exists in the symbol table. If so, it is either
663 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000664 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000665 // See if this was a redefinition. If so, there is no entry in
666 // ForwardRefVals.
667 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
668 I = ForwardRefVals.find(Name);
669 if (I == ForwardRefVals.end())
670 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
671
672 // Otherwise, this was a definition of forward ref. Verify that types
673 // agree.
674 if (Val->getType() != GA->getType())
675 return Error(NameLoc,
676 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000677
Chris Lattnerdf986172009-01-02 07:01:27 +0000678 // If they agree, just RAUW the old value with the alias and remove the
679 // forward ref info.
680 Val->replaceAllUsesWith(GA);
681 Val->eraseFromParent();
682 ForwardRefVals.erase(I);
683 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000684
Chris Lattnerdf986172009-01-02 07:01:27 +0000685 // Insert into the module, we know its name won't collide now.
686 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000687 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000688
Chris Lattnerdf986172009-01-02 07:01:27 +0000689 return false;
690}
691
692/// ParseGlobal
693/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
Michael Gottesmana2de37c2013-02-05 05:57:38 +0000694/// OptionalAddrSpace OptionalUnNammedAddr
695/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000696/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Michael Gottesmana2de37c2013-02-05 05:57:38 +0000697/// OptionalAddrSpace OptionalUnNammedAddr
698/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000699///
700/// Everything through visibility has been parsed already.
701///
702bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
703 unsigned Linkage, bool HasLinkage,
704 unsigned Visibility) {
705 unsigned AddrSpace;
Michael Gottesmana2de37c2013-02-05 05:57:38 +0000706 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
Hans Wennborgce718ff2012-06-23 11:37:03 +0000707 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000708 LocTy UnnamedAddrLoc;
Michael Gottesmana2de37c2013-02-05 05:57:38 +0000709 LocTy IsExternallyInitializedLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000710 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000711
Chris Lattner1afcace2011-07-09 17:41:24 +0000712 Type *Ty = 0;
Hans Wennborgce718ff2012-06-23 11:37:03 +0000713 if (ParseOptionalThreadLocal(TLM) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000714 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000715 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
716 &UnnamedAddrLoc) ||
Michael Gottesmana2de37c2013-02-05 05:57:38 +0000717 ParseOptionalToken(lltok::kw_externally_initialized,
718 IsExternallyInitialized,
719 &IsExternallyInitializedLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000720 ParseGlobalType(IsConstant) ||
721 ParseType(Ty, TyLoc))
722 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000723
Chris Lattnerdf986172009-01-02 07:01:27 +0000724 // If the linkage is specified and is external, then no initializer is
725 // present.
726 Constant *Init = 0;
727 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000728 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000729 Linkage != GlobalValue::ExternalLinkage)) {
730 if (ParseGlobalValue(Ty, Init))
731 return true;
732 }
733
Duncan Sands1df98592010-02-16 11:11:14 +0000734 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000735 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000736
Chris Lattnerdf986172009-01-02 07:01:27 +0000737 GlobalVariable *GV = 0;
738
739 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000740 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000741 if (GlobalValue *GVal = M->getNamedValue(Name)) {
742 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
743 return Error(NameLoc, "redefinition of global '@" + Name + "'");
744 GV = cast<GlobalVariable>(GVal);
745 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000746 } else {
747 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
748 I = ForwardRefValIDs.find(NumberedVals.size());
749 if (I != ForwardRefValIDs.end()) {
750 GV = cast<GlobalVariable>(I->second.first);
751 ForwardRefValIDs.erase(I);
752 }
753 }
754
755 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000756 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000757 Name, 0, GlobalVariable::NotThreadLocal,
758 AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000759 } else {
760 if (GV->getType()->getElementType() != Ty)
761 return Error(TyLoc,
762 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000763
Chris Lattnerdf986172009-01-02 07:01:27 +0000764 // Move the forward-reference to the correct spot in the module.
765 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
766 }
767
768 if (Name.empty())
769 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000770
Chris Lattnerdf986172009-01-02 07:01:27 +0000771 // Set the parsed properties on the global.
772 if (Init)
773 GV->setInitializer(Init);
774 GV->setConstant(IsConstant);
775 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
776 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Michael Gottesmana2de37c2013-02-05 05:57:38 +0000777 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgce718ff2012-06-23 11:37:03 +0000778 GV->setThreadLocalMode(TLM);
Rafael Espindolabea46262011-01-08 16:42:36 +0000779 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000780
Chris Lattnerdf986172009-01-02 07:01:27 +0000781 // Parse attributes on the global.
782 while (Lex.getKind() == lltok::comma) {
783 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000784
Chris Lattnerdf986172009-01-02 07:01:27 +0000785 if (Lex.getKind() == lltok::kw_section) {
786 Lex.Lex();
787 GV->setSection(Lex.getStrVal());
788 if (ParseToken(lltok::StringConstant, "expected global section string"))
789 return true;
790 } else if (Lex.getKind() == lltok::kw_align) {
791 unsigned Alignment;
792 if (ParseOptionalAlignment(Alignment)) return true;
793 GV->setAlignment(Alignment);
794 } else {
795 TokError("unknown global variable property!");
796 }
797 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000798
Chris Lattnerdf986172009-01-02 07:01:27 +0000799 return false;
800}
801
Bill Wendling95ce4c22013-02-06 06:52:58 +0000802/// ParseUnnamedAttrGrp
803/// ::= AttrGrpID '=' '{' AttrValPair+ '}'
804bool LLParser::ParseUnnamedAttrGrp() {
805 assert(Lex.getKind() == lltok::AttrGrpID);
806 LocTy AttrGrpLoc = Lex.getLoc();
807 unsigned VarID = Lex.getUIntVal();
Bill Wendlingbaad55c2013-02-08 06:32:06 +0000808 std::vector<unsigned> unused;
Bill Wendling95ce4c22013-02-06 06:52:58 +0000809 Lex.Lex();
810
811 if (ParseToken(lltok::equal, "expected '=' here") ||
812 ParseToken(lltok::kw_attributes, "expected 'attributes' keyword here") ||
813 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendlingbaad55c2013-02-08 06:32:06 +0000814 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true) ||
Bill Wendling95ce4c22013-02-06 06:52:58 +0000815 ParseToken(lltok::rbrace, "expected end of attribute group"))
816 return true;
817
Bill Wendlingbaad55c2013-02-08 06:32:06 +0000818 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling95ce4c22013-02-06 06:52:58 +0000819 return Error(AttrGrpLoc, "attribute group has no attributes");
820
821 return false;
822}
823
Bill Wendlingea007fa2013-02-08 00:52:31 +0000824/// ParseFnAttributeValuePairs
Bill Wendling95ce4c22013-02-06 06:52:58 +0000825/// ::= <attr> | <attr> '=' <value>
Bill Wendlingbaad55c2013-02-08 06:32:06 +0000826bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
827 std::vector<unsigned> &FwdRefAttrGrps,
828 bool inAttrGrp) {
Bill Wendlingea007fa2013-02-08 00:52:31 +0000829 bool HaveError = false;
830
831 B.clear();
832
Bill Wendling95ce4c22013-02-06 06:52:58 +0000833 while (true) {
834 lltok::Kind Token = Lex.getKind();
835 switch (Token) {
836 default:
Bill Wendlingea007fa2013-02-08 00:52:31 +0000837 if (!inAttrGrp) return HaveError;
Bill Wendling95ce4c22013-02-06 06:52:58 +0000838 return Error(Lex.getLoc(), "unterminated attribute group");
839 case lltok::rbrace:
840 // Finished.
841 return false;
842
Bill Wendlingbaad55c2013-02-08 06:32:06 +0000843 case lltok::AttrGrpID: {
844 // Allow a function to reference an attribute group:
845 //
846 // define void @foo() #1 { ... }
847 if (inAttrGrp)
848 HaveError |=
849 Error(Lex.getLoc(),
850 "cannot have an attribute group reference in an attribute group");
851
852 unsigned AttrGrpNum = Lex.getUIntVal();
853 if (inAttrGrp) break;
854
855 // Save the reference to the attribute group. We'll fill it in later.
856 FwdRefAttrGrps.push_back(AttrGrpNum);
857 break;
858 }
Bill Wendling95ce4c22013-02-06 06:52:58 +0000859 // Target-dependent attributes:
860 case lltok::StringConstant: {
861 std::string Attr = Lex.getStrVal();
862 Lex.Lex();
863 std::string Val;
864 if (EatIfPresent(lltok::equal) &&
865 ParseStringConstant(Val))
866 return true;
867
868 B.addAttribute(Attr, Val);
869 break;
870 }
871
872 // Target-independent attributes:
873 case lltok::kw_align: {
Bill Wendlingea007fa2013-02-08 00:52:31 +0000874 // As a hack, we allow "align 2" on functions as a synonym for "alignstack
875 // 2".
Bill Wendling95ce4c22013-02-06 06:52:58 +0000876 unsigned Alignment;
Bill Wendlingea007fa2013-02-08 00:52:31 +0000877 if (inAttrGrp) {
878 if (ParseToken(lltok::equal, "expected '=' here") ||
879 ParseUInt32(Alignment))
880 return true;
881 } else {
882 if (ParseOptionalAlignment(Alignment))
883 return true;
884 }
Bill Wendling95ce4c22013-02-06 06:52:58 +0000885 B.addAlignmentAttr(Alignment);
Bill Wendlingea007fa2013-02-08 00:52:31 +0000886 continue;
Bill Wendling95ce4c22013-02-06 06:52:58 +0000887 }
888 case lltok::kw_alignstack: {
889 unsigned Alignment;
Bill Wendlingea007fa2013-02-08 00:52:31 +0000890 if (inAttrGrp) {
891 if (ParseToken(lltok::equal, "expected '=' here") ||
892 ParseUInt32(Alignment))
893 return true;
894 } else {
895 if (ParseOptionalStackAlignment(Alignment))
896 return true;
897 }
Bill Wendling95ce4c22013-02-06 06:52:58 +0000898 B.addStackAlignmentAttr(Alignment);
Bill Wendlingea007fa2013-02-08 00:52:31 +0000899 continue;
Bill Wendling95ce4c22013-02-06 06:52:58 +0000900 }
901 case lltok::kw_address_safety: B.addAttribute(Attribute::AddressSafety); break;
902 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Bill Wendling95ce4c22013-02-06 06:52:58 +0000903 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Bill Wendling95ce4c22013-02-06 06:52:58 +0000904 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
905 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
Bill Wendling95ce4c22013-02-06 06:52:58 +0000906 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
907 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
908 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
909 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
910 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
911 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
912 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
913 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
914 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
915 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
916 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
Bill Wendling95ce4c22013-02-06 06:52:58 +0000917 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
918 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
919 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
920 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendlingea007fa2013-02-08 00:52:31 +0000921
922 // Error handling.
923 case lltok::kw_inreg:
924 case lltok::kw_signext:
925 case lltok::kw_zeroext:
926 HaveError |=
927 Error(Lex.getLoc(),
928 "invalid use of attribute on a function");
929 break;
930 case lltok::kw_byval:
931 case lltok::kw_nest:
932 case lltok::kw_noalias:
933 case lltok::kw_nocapture:
934 case lltok::kw_sret:
935 HaveError |=
936 Error(Lex.getLoc(),
937 "invalid use of parameter-only attribute on a function");
938 break;
Bill Wendling95ce4c22013-02-06 06:52:58 +0000939 }
940
941 Lex.Lex();
942 }
943}
Chris Lattnerdf986172009-01-02 07:01:27 +0000944
945//===----------------------------------------------------------------------===//
946// GlobalValue Reference/Resolution Routines.
947//===----------------------------------------------------------------------===//
948
949/// GetGlobalVal - Get a value with the specified name or ID, creating a
950/// forward reference record if needed. This can return null if the value
951/// exists but does not have the right type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000952GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +0000953 LocTy Loc) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000954 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000955 if (PTy == 0) {
956 Error(Loc, "global variable reference must have pointer type");
957 return 0;
958 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000959
Chris Lattnerdf986172009-01-02 07:01:27 +0000960 // Look this name up in the normal function symbol table.
961 GlobalValue *Val =
962 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000963
Chris Lattnerdf986172009-01-02 07:01:27 +0000964 // If this is a forward reference for the value, see if we already created a
965 // forward ref record.
966 if (Val == 0) {
967 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
968 I = ForwardRefVals.find(Name);
969 if (I != ForwardRefVals.end())
970 Val = I->second.first;
971 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000972
Chris Lattnerdf986172009-01-02 07:01:27 +0000973 // If we have the value in the symbol table or fwd-ref table, return it.
974 if (Val) {
975 if (Val->getType() == Ty) return Val;
976 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000977 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000978 return 0;
979 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000980
Chris Lattnerdf986172009-01-02 07:01:27 +0000981 // Otherwise, create a new forward reference for this value and remember it.
982 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000983 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000984 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000985 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000986 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Justin Holewinskieaff2d52012-11-16 21:03:47 +0000987 GlobalValue::ExternalWeakLinkage, 0, Name,
988 0, GlobalVariable::NotThreadLocal,
989 PTy->getAddressSpace());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000990
Chris Lattnerdf986172009-01-02 07:01:27 +0000991 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
992 return FwdVal;
993}
994
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000995GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
996 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000997 if (PTy == 0) {
998 Error(Loc, "global variable reference must have pointer type");
999 return 0;
1000 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001001
Chris Lattnerdf986172009-01-02 07:01:27 +00001002 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001003
Chris Lattnerdf986172009-01-02 07:01:27 +00001004 // If this is a forward reference for the value, see if we already created a
1005 // forward ref record.
1006 if (Val == 0) {
1007 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1008 I = ForwardRefValIDs.find(ID);
1009 if (I != ForwardRefValIDs.end())
1010 Val = I->second.first;
1011 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001012
Chris Lattnerdf986172009-01-02 07:01:27 +00001013 // If we have the value in the symbol table or fwd-ref table, return it.
1014 if (Val) {
1015 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001016 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001017 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001018 return 0;
1019 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001020
Chris Lattnerdf986172009-01-02 07:01:27 +00001021 // Otherwise, create a new forward reference for this value and remember it.
1022 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001023 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00001024 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner1afcace2011-07-09 17:41:24 +00001025 else
Owen Andersone9b11b42009-07-08 19:03:57 +00001026 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1027 GlobalValue::ExternalWeakLinkage, 0, "");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001028
Chris Lattnerdf986172009-01-02 07:01:27 +00001029 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1030 return FwdVal;
1031}
1032
1033
1034//===----------------------------------------------------------------------===//
1035// Helper Routines.
1036//===----------------------------------------------------------------------===//
1037
1038/// ParseToken - If the current token has the specified kind, eat it and return
1039/// success. Otherwise, emit the specified error and return failure.
1040bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1041 if (Lex.getKind() != T)
1042 return TokError(ErrMsg);
1043 Lex.Lex();
1044 return false;
1045}
1046
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001047/// ParseStringConstant
1048/// ::= StringConstant
1049bool LLParser::ParseStringConstant(std::string &Result) {
1050 if (Lex.getKind() != lltok::StringConstant)
1051 return TokError("expected string constant");
1052 Result = Lex.getStrVal();
1053 Lex.Lex();
1054 return false;
1055}
1056
1057/// ParseUInt32
1058/// ::= uint32
1059bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001060 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1061 return TokError("expected integer");
1062 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1063 if (Val64 != unsigned(Val64))
1064 return TokError("expected 32-bit integer (too large)");
1065 Val = Val64;
1066 Lex.Lex();
1067 return false;
1068}
1069
Hans Wennborgce718ff2012-06-23 11:37:03 +00001070/// ParseTLSModel
1071/// := 'localdynamic'
1072/// := 'initialexec'
1073/// := 'localexec'
1074bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1075 switch (Lex.getKind()) {
1076 default:
1077 return TokError("expected localdynamic, initialexec or localexec");
1078 case lltok::kw_localdynamic:
1079 TLM = GlobalVariable::LocalDynamicTLSModel;
1080 break;
1081 case lltok::kw_initialexec:
1082 TLM = GlobalVariable::InitialExecTLSModel;
1083 break;
1084 case lltok::kw_localexec:
1085 TLM = GlobalVariable::LocalExecTLSModel;
1086 break;
1087 }
1088
1089 Lex.Lex();
1090 return false;
1091}
1092
1093/// ParseOptionalThreadLocal
1094/// := /*empty*/
1095/// := 'thread_local'
1096/// := 'thread_local' '(' tlsmodel ')'
1097bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1098 TLM = GlobalVariable::NotThreadLocal;
1099 if (!EatIfPresent(lltok::kw_thread_local))
1100 return false;
1101
1102 TLM = GlobalVariable::GeneralDynamicTLSModel;
1103 if (Lex.getKind() == lltok::lparen) {
1104 Lex.Lex();
1105 return ParseTLSModel(TLM) ||
1106 ParseToken(lltok::rparen, "expected ')' after thread local model");
1107 }
1108 return false;
1109}
Chris Lattnerdf986172009-01-02 07:01:27 +00001110
1111/// ParseOptionalAddrSpace
1112/// := /*empty*/
1113/// := 'addrspace' '(' uint32 ')'
1114bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1115 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001116 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +00001117 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001118 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001119 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001120 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001121}
Chris Lattnerdf986172009-01-02 07:01:27 +00001122
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001123/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1124bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1125 bool HaveError = false;
1126
1127 B.clear();
1128
1129 while (1) {
1130 lltok::Kind Token = Lex.getKind();
1131 switch (Token) {
1132 default: // End of attributes.
1133 return HaveError;
Chris Lattnerdf986172009-01-02 07:01:27 +00001134 case lltok::kw_align: {
1135 unsigned Alignment;
1136 if (ParseOptionalAlignment(Alignment))
1137 return true;
Bill Wendling03272442012-10-08 22:20:14 +00001138 B.addAlignmentAttr(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00001139 continue;
1140 }
Bill Wendling034b94b2012-12-19 07:18:57 +00001141 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1142 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1143 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1144 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1145 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1146 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1147 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1148 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davis1e063d12010-02-12 00:31:15 +00001149
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001150 case lltok::kw_noreturn: case lltok::kw_nounwind:
1151 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1152 case lltok::kw_noinline: case lltok::kw_readnone:
1153 case lltok::kw_readonly: case lltok::kw_inlinehint:
1154 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1155 case lltok::kw_ssp: case lltok::kw_sspreq:
1156 case lltok::kw_noredzone: case lltok::kw_noimplicitfloat:
1157 case lltok::kw_naked: case lltok::kw_nonlazybind:
1158 case lltok::kw_address_safety: case lltok::kw_minsize:
1159 case lltok::kw_alignstack:
1160 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1161 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001162 }
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001163
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001164 Lex.Lex();
1165 }
1166}
1167
1168/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1169bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1170 bool HaveError = false;
1171
1172 B.clear();
1173
1174 while (1) {
1175 lltok::Kind Token = Lex.getKind();
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001176 switch (Token) {
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001177 default: // End of attributes.
1178 return HaveError;
Bill Wendling034b94b2012-12-19 07:18:57 +00001179 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1180 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1181 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1182 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001183
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001184 // Error handling.
1185 case lltok::kw_sret: case lltok::kw_nocapture:
1186 case lltok::kw_byval: case lltok::kw_nest:
1187 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001188 break;
James Molloy67ae1352012-12-20 16:04:27 +00001189
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001190 case lltok::kw_noreturn: case lltok::kw_nounwind:
1191 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1192 case lltok::kw_noinline: case lltok::kw_readnone:
1193 case lltok::kw_readonly: case lltok::kw_inlinehint:
1194 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1195 case lltok::kw_ssp: case lltok::kw_sspreq:
Bill Wendling114baee2013-01-23 06:41:41 +00001196 case lltok::kw_sspstrong: case lltok::kw_noimplicitfloat:
1197 case lltok::kw_noredzone: case lltok::kw_naked:
1198 case lltok::kw_nonlazybind: case lltok::kw_address_safety:
1199 case lltok::kw_minsize: case lltok::kw_alignstack:
1200 case lltok::kw_align: case lltok::kw_noduplicate:
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001201 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001202 break;
1203 }
1204
Chris Lattnerdf986172009-01-02 07:01:27 +00001205 Lex.Lex();
1206 }
1207}
1208
1209/// ParseOptionalLinkage
1210/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001211/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001212/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001213/// ::= 'linker_private_weak'
Chris Lattnerdf986172009-01-02 07:01:27 +00001214/// ::= 'internal'
1215/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001216/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001217/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001218/// ::= 'linkonce_odr'
Bill Wendling32811be2012-08-17 18:33:14 +00001219/// ::= 'linkonce_odr_auto_hide'
Bill Wendling5e721d72010-07-01 21:55:59 +00001220/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001221/// ::= 'appending'
1222/// ::= 'dllexport'
1223/// ::= 'common'
1224/// ::= 'dllimport'
1225/// ::= 'extern_weak'
1226/// ::= 'external'
1227bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1228 HasLinkage = false;
1229 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001230 default: Res=GlobalValue::ExternalLinkage; return false;
1231 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1232 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001233 case lltok::kw_linker_private_weak:
1234 Res = GlobalValue::LinkerPrivateWeakLinkage;
1235 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001236 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1237 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1238 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1239 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1240 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Bill Wendling32811be2012-08-17 18:33:14 +00001241 case lltok::kw_linkonce_odr_auto_hide:
1242 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1243 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1244 break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001245 case lltok::kw_available_externally:
1246 Res = GlobalValue::AvailableExternallyLinkage;
1247 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001248 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1249 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1250 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1251 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1252 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1253 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001254 }
1255 Lex.Lex();
1256 HasLinkage = true;
1257 return false;
1258}
1259
1260/// ParseOptionalVisibility
1261/// ::= /*empty*/
1262/// ::= 'default'
1263/// ::= 'hidden'
1264/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001265///
Chris Lattnerdf986172009-01-02 07:01:27 +00001266bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1267 switch (Lex.getKind()) {
1268 default: Res = GlobalValue::DefaultVisibility; return false;
1269 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1270 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1271 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1272 }
1273 Lex.Lex();
1274 return false;
1275}
1276
1277/// ParseOptionalCallingConv
1278/// ::= /*empty*/
1279/// ::= 'ccc'
1280/// ::= 'fastcc'
Elena Demikhovsky35752222012-10-24 14:46:16 +00001281/// ::= 'kw_intel_ocl_bicc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001282/// ::= 'coldcc'
1283/// ::= 'x86_stdcallcc'
1284/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001285/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001286/// ::= 'arm_apcscc'
1287/// ::= 'arm_aapcscc'
1288/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001289/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001290/// ::= 'ptx_kernel'
1291/// ::= 'ptx_device'
Micah Villmowe53d6052012-10-01 17:01:31 +00001292/// ::= 'spir_func'
1293/// ::= 'spir_kernel'
Chris Lattnerdf986172009-01-02 07:01:27 +00001294/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001295///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001296bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001297 switch (Lex.getKind()) {
1298 default: CC = CallingConv::C; return false;
1299 case lltok::kw_ccc: CC = CallingConv::C; break;
1300 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1301 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1302 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1303 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001304 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001305 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1306 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1307 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001308 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001309 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1310 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmowe53d6052012-10-01 17:01:31 +00001311 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1312 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovsky35752222012-10-24 14:46:16 +00001313 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001314 case lltok::kw_cc: {
1315 unsigned ArbitraryCC;
1316 Lex.Lex();
David Blaikie4d6ccb52012-01-20 21:51:11 +00001317 if (ParseUInt32(ArbitraryCC))
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001318 return true;
David Blaikie4d6ccb52012-01-20 21:51:11 +00001319 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1320 return false;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001321 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001322 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001323
Chris Lattnerdf986172009-01-02 07:01:27 +00001324 Lex.Lex();
1325 return false;
1326}
1327
Chris Lattnerb8c46862009-12-30 05:31:19 +00001328/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001329/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001330bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1331 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001332 do {
1333 if (Lex.getKind() != lltok::MetadataVar)
1334 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001335
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001336 std::string Name = Lex.getStrVal();
Benjamin Kramer85dadec2011-12-06 11:50:26 +00001337 unsigned MDK = M->getMDKindID(Name);
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001338 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001339
Chris Lattner442ffa12009-12-29 21:53:55 +00001340 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001341 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001342
1343 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001344 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001345
Dan Gohman68261142010-08-24 14:35:45 +00001346 // This code is similar to that of ParseMetadataValue, however it needs to
1347 // have special-case code for a forward reference; see the comments on
1348 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1349 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001350 if (Lex.getKind() == lltok::lbrace) {
1351 ValID ID;
1352 if (ParseMetadataListValue(ID, PFS))
1353 return true;
1354 assert(ID.Kind == ValID::t_MDNode);
1355 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001356 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001357 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001358 if (ParseMDNodeID(Node, NodeID))
1359 return true;
1360 if (Node) {
1361 // If we got the node, add it to the instruction.
1362 Inst->setMetadata(MDK, Node);
1363 } else {
1364 MDRef R = { Loc, MDK, NodeID };
1365 // Otherwise, remember that this should be resolved later.
1366 ForwardRefInstMetadata[Inst].push_back(R);
1367 }
Chris Lattner449c3102010-04-01 05:14:45 +00001368 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001369
1370 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001371 } while (EatIfPresent(lltok::comma));
1372 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001373}
1374
Chris Lattnerdf986172009-01-02 07:01:27 +00001375/// ParseOptionalAlignment
1376/// ::= /* empty */
1377/// ::= 'align' 4
1378bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1379 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001380 if (!EatIfPresent(lltok::kw_align))
1381 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001382 LocTy AlignLoc = Lex.getLoc();
1383 if (ParseUInt32(Alignment)) return true;
1384 if (!isPowerOf2_32(Alignment))
1385 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001386 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001387 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001388 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001389}
1390
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001391/// ParseOptionalCommaAlign
Michael Ilseman407a6162012-11-15 22:34:00 +00001392/// ::=
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001393/// ::= ',' align 4
1394///
1395/// This returns with AteExtraComma set to true if it ate an excess comma at the
1396/// end.
1397bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1398 bool &AteExtraComma) {
1399 AteExtraComma = false;
1400 while (EatIfPresent(lltok::comma)) {
1401 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001402 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001403 AteExtraComma = true;
1404 return false;
1405 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001406
Chris Lattner093eed12010-04-23 00:50:50 +00001407 if (Lex.getKind() != lltok::kw_align)
1408 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001409
Chris Lattner093eed12010-04-23 00:50:50 +00001410 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001411 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001412
Devang Patelf633a062009-09-17 23:04:48 +00001413 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001414}
1415
Eli Friedman47f35132011-07-25 23:16:38 +00001416/// ParseScopeAndOrdering
1417/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1418/// else: ::=
1419///
1420/// This sets Scope and Ordering to the parsed values.
1421bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1422 AtomicOrdering &Ordering) {
1423 if (!isAtomic)
1424 return false;
1425
1426 Scope = CrossThread;
1427 if (EatIfPresent(lltok::kw_singlethread))
1428 Scope = SingleThread;
1429 switch (Lex.getKind()) {
1430 default: return TokError("Expected ordering on atomic instruction");
1431 case lltok::kw_unordered: Ordering = Unordered; break;
1432 case lltok::kw_monotonic: Ordering = Monotonic; break;
1433 case lltok::kw_acquire: Ordering = Acquire; break;
1434 case lltok::kw_release: Ordering = Release; break;
1435 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1436 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1437 }
1438 Lex.Lex();
1439 return false;
1440}
1441
Charles Davis1e063d12010-02-12 00:31:15 +00001442/// ParseOptionalStackAlignment
1443/// ::= /* empty */
1444/// ::= 'alignstack' '(' 4 ')'
1445bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1446 Alignment = 0;
1447 if (!EatIfPresent(lltok::kw_alignstack))
1448 return false;
1449 LocTy ParenLoc = Lex.getLoc();
1450 if (!EatIfPresent(lltok::lparen))
1451 return Error(ParenLoc, "expected '('");
1452 LocTy AlignLoc = Lex.getLoc();
1453 if (ParseUInt32(Alignment)) return true;
1454 ParenLoc = Lex.getLoc();
1455 if (!EatIfPresent(lltok::rparen))
1456 return Error(ParenLoc, "expected ')'");
1457 if (!isPowerOf2_32(Alignment))
1458 return Error(AlignLoc, "stack alignment is not a power of two");
1459 return false;
1460}
Devang Patelf633a062009-09-17 23:04:48 +00001461
Chris Lattner628c13a2009-12-30 05:14:00 +00001462/// ParseIndexList - This parses the index list for an insert/extractvalue
1463/// instruction. This sets AteExtraComma in the case where we eat an extra
1464/// comma at the end of the line and find that it is followed by metadata.
1465/// Clients that don't allow metadata can call the version of this function that
1466/// only takes one argument.
1467///
Chris Lattnerdf986172009-01-02 07:01:27 +00001468/// ParseIndexList
1469/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001470///
1471bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1472 bool &AteExtraComma) {
1473 AteExtraComma = false;
Michael Ilseman407a6162012-11-15 22:34:00 +00001474
Chris Lattnerdf986172009-01-02 07:01:27 +00001475 if (Lex.getKind() != lltok::comma)
1476 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001477
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001478 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001479 if (Lex.getKind() == lltok::MetadataVar) {
1480 AteExtraComma = true;
1481 return false;
1482 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001483 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001484 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001485 Indices.push_back(Idx);
1486 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001487
Chris Lattnerdf986172009-01-02 07:01:27 +00001488 return false;
1489}
1490
1491//===----------------------------------------------------------------------===//
1492// Type Parsing.
1493//===----------------------------------------------------------------------===//
1494
Chris Lattner1afcace2011-07-09 17:41:24 +00001495/// ParseType - Parse a type.
1496bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1497 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001498 switch (Lex.getKind()) {
1499 default:
1500 return TokError("expected type");
1501 case lltok::Type:
Chris Lattner1afcace2011-07-09 17:41:24 +00001502 // Type ::= 'float' | 'void' (etc)
Chris Lattnerdf986172009-01-02 07:01:27 +00001503 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001504 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001505 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001506 case lltok::lbrace:
Chris Lattner1afcace2011-07-09 17:41:24 +00001507 // Type ::= StructType
1508 if (ParseAnonStructType(Result, false))
Chris Lattnerdf986172009-01-02 07:01:27 +00001509 return true;
1510 break;
1511 case lltok::lsquare:
Chris Lattner1afcace2011-07-09 17:41:24 +00001512 // Type ::= '[' ... ']'
Chris Lattnerdf986172009-01-02 07:01:27 +00001513 Lex.Lex(); // eat the lsquare.
1514 if (ParseArrayVectorType(Result, false))
1515 return true;
1516 break;
1517 case lltok::less: // Either vector or packed struct.
Chris Lattner1afcace2011-07-09 17:41:24 +00001518 // Type ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001519 Lex.Lex();
1520 if (Lex.getKind() == lltok::lbrace) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001521 if (ParseAnonStructType(Result, true) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001522 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001523 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001524 } else if (ParseArrayVectorType(Result, true))
1525 return true;
1526 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001527 case lltok::LocalVar: {
1528 // Type ::= %foo
1529 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman407a6162012-11-15 22:34:00 +00001530
Chris Lattner1afcace2011-07-09 17:41:24 +00001531 // If the type hasn't been defined yet, create a forward definition and
1532 // remember where that forward def'n was seen (in case it never is defined).
1533 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001534 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattner1afcace2011-07-09 17:41:24 +00001535 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001536 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001537 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001538 Lex.Lex();
1539 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001540 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001541
Chris Lattner1afcace2011-07-09 17:41:24 +00001542 case lltok::LocalVarID: {
1543 // Type ::= %4
1544 if (Lex.getUIntVal() >= NumberedTypes.size())
1545 NumberedTypes.resize(Lex.getUIntVal()+1);
1546 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman407a6162012-11-15 22:34:00 +00001547
Chris Lattner1afcace2011-07-09 17:41:24 +00001548 // If the type hasn't been defined yet, create a forward definition and
1549 // remember where that forward def'n was seen (in case it never is defined).
1550 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001551 Entry.first = StructType::create(Context);
Chris Lattner1afcace2011-07-09 17:41:24 +00001552 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001553 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001554 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001555 Lex.Lex();
1556 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001557 }
1558 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001559
1560 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001561 while (1) {
1562 switch (Lex.getKind()) {
1563 // End of type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001564 default:
1565 if (!AllowVoid && Result->isVoidTy())
1566 return Error(TypeLoc, "void type only allowed for function results");
1567 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001568
Chris Lattner1afcace2011-07-09 17:41:24 +00001569 // Type ::= Type '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001570 case lltok::star:
Chris Lattner1afcace2011-07-09 17:41:24 +00001571 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001572 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001573 if (Result->isVoidTy())
1574 return TokError("pointers to void are invalid - use i8* instead");
1575 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001576 return TokError("pointer to this type is invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001577 Result = PointerType::getUnqual(Result);
Chris Lattnerdf986172009-01-02 07:01:27 +00001578 Lex.Lex();
1579 break;
1580
Chris Lattner1afcace2011-07-09 17:41:24 +00001581 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001582 case lltok::kw_addrspace: {
Chris Lattner1afcace2011-07-09 17:41:24 +00001583 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001584 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001585 if (Result->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001586 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattner1afcace2011-07-09 17:41:24 +00001587 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001588 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001589 unsigned AddrSpace;
1590 if (ParseOptionalAddrSpace(AddrSpace) ||
1591 ParseToken(lltok::star, "expected '*' in address space"))
1592 return true;
1593
Chris Lattner1afcace2011-07-09 17:41:24 +00001594 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001595 break;
1596 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001597
Chris Lattnerdf986172009-01-02 07:01:27 +00001598 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1599 case lltok::lparen:
1600 if (ParseFunctionType(Result))
1601 return true;
1602 break;
1603 }
1604 }
1605}
1606
1607/// ParseParameterList
1608/// ::= '(' ')'
1609/// ::= '(' Arg (',' Arg)* ')'
1610/// Arg
1611/// ::= Type OptionalAttributes Value OptionalAttributes
1612bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1613 PerFunctionState &PFS) {
1614 if (ParseToken(lltok::lparen, "expected '(' in call"))
1615 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001616
Bill Wendling73dee182013-01-31 00:29:54 +00001617 unsigned AttrIndex = 1;
Chris Lattnerdf986172009-01-02 07:01:27 +00001618 while (Lex.getKind() != lltok::rparen) {
1619 // If this isn't the first argument, we need a comma.
1620 if (!ArgList.empty() &&
1621 ParseToken(lltok::comma, "expected ',' in argument list"))
1622 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001623
Chris Lattnerdf986172009-01-02 07:01:27 +00001624 // Parse the argument.
1625 LocTy ArgLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +00001626 Type *ArgTy = 0;
Bill Wendling702cc912012-10-15 20:35:56 +00001627 AttrBuilder ArgAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001628 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001629 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001630 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001631
Chris Lattner287881d2009-12-30 02:11:14 +00001632 // Otherwise, handle normal operands.
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001633 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001634 return true;
Bill Wendling73dee182013-01-31 00:29:54 +00001635 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1636 AttrIndex++,
1637 ArgAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00001638 }
1639
1640 Lex.Lex(); // Lex the ')'.
1641 return false;
1642}
1643
1644
1645
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001646/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattner1afcace2011-07-09 17:41:24 +00001647/// prototype.
Chris Lattnerdf986172009-01-02 07:01:27 +00001648/// ::= '(' ArgTypeListI ')'
1649/// ArgTypeListI
1650/// ::= /*empty*/
1651/// ::= '...'
1652/// ::= ArgTypeList ',' '...'
1653/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001654///
Chris Lattner1afcace2011-07-09 17:41:24 +00001655bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1656 bool &isVarArg){
Chris Lattnerdf986172009-01-02 07:01:27 +00001657 isVarArg = false;
1658 assert(Lex.getKind() == lltok::lparen);
1659 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001660
Chris Lattnerdf986172009-01-02 07:01:27 +00001661 if (Lex.getKind() == lltok::rparen) {
1662 // empty
1663 } else if (Lex.getKind() == lltok::dotdotdot) {
1664 isVarArg = true;
1665 Lex.Lex();
1666 } else {
1667 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001668 Type *ArgTy = 0;
Bill Wendling702cc912012-10-15 20:35:56 +00001669 AttrBuilder Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001670 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001671
Chris Lattner1afcace2011-07-09 17:41:24 +00001672 if (ParseType(ArgTy) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001673 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001674
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001675 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001676 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001677
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001678 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001679 Name = Lex.getStrVal();
1680 Lex.Lex();
1681 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001682
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001683 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001684 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001685
Bill Wendling73dee182013-01-31 00:29:54 +00001686 unsigned AttrIndex = 1;
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001687 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendling73dee182013-01-31 00:29:54 +00001688 AttributeSet::get(ArgTy->getContext(),
1689 AttrIndex++, Attrs), Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001690
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001691 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001692 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001693 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001694 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001695 break;
1696 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001697
Chris Lattnerdf986172009-01-02 07:01:27 +00001698 // Otherwise must be an argument type.
1699 TypeLoc = Lex.getLoc();
Bill Wendlinge01b81b2012-12-04 23:40:58 +00001700 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001701
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001702 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001703 return Error(TypeLoc, "argument can not have void type");
1704
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001705 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001706 Name = Lex.getStrVal();
1707 Lex.Lex();
1708 } else {
1709 Name = "";
1710 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001711
Chris Lattner1afcace2011-07-09 17:41:24 +00001712 if (!ArgTy->isFirstClassType())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001713 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001714
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001715 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendling73dee182013-01-31 00:29:54 +00001716 AttributeSet::get(ArgTy->getContext(),
1717 AttrIndex++, Attrs),
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001718 Name));
Chris Lattnerdf986172009-01-02 07:01:27 +00001719 }
1720 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001721
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001722 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001723}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001724
Chris Lattnerdf986172009-01-02 07:01:27 +00001725/// ParseFunctionType
1726/// ::= Type ArgumentList OptionalAttrs
Chris Lattner1afcace2011-07-09 17:41:24 +00001727bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001728 assert(Lex.getKind() == lltok::lparen);
1729
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001730 if (!FunctionType::isValidReturnType(Result))
1731 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001732
Chris Lattner1afcace2011-07-09 17:41:24 +00001733 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00001734 bool isVarArg;
Chris Lattner1afcace2011-07-09 17:41:24 +00001735 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerdf986172009-01-02 07:01:27 +00001736 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001737
Chris Lattnerdf986172009-01-02 07:01:27 +00001738 // Reject names on the arguments lists.
1739 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1740 if (!ArgList[i].Name.empty())
1741 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendling73dee182013-01-31 00:29:54 +00001742 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattnera16546a2011-06-17 17:37:13 +00001743 return Error(ArgList[i].Loc,
1744 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001745 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001746
Jay Foad5fdd6c82011-07-12 14:06:48 +00001747 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerdf986172009-01-02 07:01:27 +00001748 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattner1afcace2011-07-09 17:41:24 +00001749 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001750
Chris Lattner1afcace2011-07-09 17:41:24 +00001751 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerdf986172009-01-02 07:01:27 +00001752 return false;
1753}
1754
Chris Lattner1afcace2011-07-09 17:41:24 +00001755/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1756/// other structs.
1757bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1758 SmallVector<Type*, 8> Elts;
1759 if (ParseStructBody(Elts)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001760
Chris Lattner1afcace2011-07-09 17:41:24 +00001761 Result = StructType::get(Context, Elts, Packed);
1762 return false;
1763}
1764
1765/// ParseStructDefinition - Parse a struct in a 'type' definition.
1766bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1767 std::pair<Type*, LocTy> &Entry,
1768 Type *&ResultTy) {
1769 // If the type was already defined, diagnose the redefinition.
1770 if (Entry.first && !Entry.second.isValid())
1771 return Error(TypeLoc, "redefinition of type");
Michael Ilseman407a6162012-11-15 22:34:00 +00001772
Chris Lattner1afcace2011-07-09 17:41:24 +00001773 // If we have opaque, just return without filling in the definition for the
1774 // struct. This counts as a definition as far as the .ll file goes.
1775 if (EatIfPresent(lltok::kw_opaque)) {
1776 // This type is being defined, so clear the location to indicate this.
1777 Entry.second = SMLoc();
Michael Ilseman407a6162012-11-15 22:34:00 +00001778
Chris Lattner1afcace2011-07-09 17:41:24 +00001779 // If this type number has never been uttered, create it.
1780 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001781 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001782 ResultTy = Entry.first;
1783 return false;
1784 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001785
Chris Lattner1afcace2011-07-09 17:41:24 +00001786 // If the type starts with '<', then it is either a packed struct or a vector.
1787 bool isPacked = EatIfPresent(lltok::less);
1788
1789 // If we don't have a struct, then we have a random type alias, which we
1790 // accept for compatibility with old files. These types are not allowed to be
1791 // forward referenced and not allowed to be recursive.
1792 if (Lex.getKind() != lltok::lbrace) {
1793 if (Entry.first)
1794 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman407a6162012-11-15 22:34:00 +00001795
Chris Lattner1afcace2011-07-09 17:41:24 +00001796 ResultTy = 0;
1797 if (isPacked)
1798 return ParseArrayVectorType(ResultTy, true);
1799 return ParseType(ResultTy);
1800 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001801
Chris Lattner1afcace2011-07-09 17:41:24 +00001802 // This type is being defined, so clear the location to indicate this.
1803 Entry.second = SMLoc();
Michael Ilseman407a6162012-11-15 22:34:00 +00001804
Chris Lattner1afcace2011-07-09 17:41:24 +00001805 // If this type number has never been uttered, create it.
1806 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001807 Entry.first = StructType::create(Context, Name);
Michael Ilseman407a6162012-11-15 22:34:00 +00001808
Chris Lattner1afcace2011-07-09 17:41:24 +00001809 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman407a6162012-11-15 22:34:00 +00001810
Chris Lattner1afcace2011-07-09 17:41:24 +00001811 SmallVector<Type*, 8> Body;
1812 if (ParseStructBody(Body) ||
1813 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1814 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001815
Chris Lattner1afcace2011-07-09 17:41:24 +00001816 STy->setBody(Body, isPacked);
1817 ResultTy = STy;
1818 return false;
1819}
1820
1821
Chris Lattnerdf986172009-01-02 07:01:27 +00001822/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattner1afcace2011-07-09 17:41:24 +00001823/// StructType
Chris Lattnerdf986172009-01-02 07:01:27 +00001824/// ::= '{' '}'
Chris Lattner1afcace2011-07-09 17:41:24 +00001825/// ::= '{' Type (',' Type)* '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00001826/// ::= '<' '{' '}' '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001827/// ::= '<' '{' Type (',' Type)* '}' '>'
1828bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001829 assert(Lex.getKind() == lltok::lbrace);
1830 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001831
Chris Lattner1afcace2011-07-09 17:41:24 +00001832 // Handle the empty struct.
1833 if (EatIfPresent(lltok::rbrace))
Chris Lattnerdf986172009-01-02 07:01:27 +00001834 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001835
Chris Lattnera9a9e072009-03-09 04:49:14 +00001836 LocTy EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001837 Type *Ty = 0;
1838 if (ParseType(Ty)) return true;
1839 Body.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001840
Chris Lattner1afcace2011-07-09 17:41:24 +00001841 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001842 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001843
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001844 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001845 EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001846 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001847
Chris Lattner1afcace2011-07-09 17:41:24 +00001848 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001849 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001850
Chris Lattner1afcace2011-07-09 17:41:24 +00001851 Body.push_back(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00001852 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001853
Chris Lattner1afcace2011-07-09 17:41:24 +00001854 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerdf986172009-01-02 07:01:27 +00001855}
1856
1857/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1858/// token has already been consumed.
Chris Lattner1afcace2011-07-09 17:41:24 +00001859/// Type
Chris Lattnerdf986172009-01-02 07:01:27 +00001860/// ::= '[' APSINTVAL 'x' Types ']'
1861/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001862bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001863 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1864 Lex.getAPSIntVal().getBitWidth() > 64)
1865 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001866
Chris Lattnerdf986172009-01-02 07:01:27 +00001867 LocTy SizeLoc = Lex.getLoc();
1868 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001869 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001870
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001871 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1872 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001873
1874 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001875 Type *EltTy = 0;
1876 if (ParseType(EltTy)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001877
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001878 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1879 "expected end of sequential type"))
1880 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001881
Chris Lattnerdf986172009-01-02 07:01:27 +00001882 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001883 if (Size == 0)
1884 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001885 if ((unsigned)Size != Size)
1886 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001887 if (!VectorType::isValidElementType(EltTy))
Duncan Sands2333e292012-11-13 12:59:33 +00001888 return Error(TypeLoc, "invalid vector element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001889 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001890 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001891 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001892 return Error(TypeLoc, "invalid array element type");
Chris Lattner1afcace2011-07-09 17:41:24 +00001893 Result = ArrayType::get(EltTy, Size);
Chris Lattnerdf986172009-01-02 07:01:27 +00001894 }
1895 return false;
1896}
1897
1898//===----------------------------------------------------------------------===//
1899// Function Semantic Analysis.
1900//===----------------------------------------------------------------------===//
1901
Chris Lattner09d9ef42009-10-28 03:39:23 +00001902LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1903 int functionNumber)
1904 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001905
1906 // Insert unnamed arguments into the NumberedVals list.
1907 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1908 AI != E; ++AI)
1909 if (!AI->hasName())
1910 NumberedVals.push_back(AI);
1911}
1912
1913LLParser::PerFunctionState::~PerFunctionState() {
1914 // If there were any forward referenced non-basicblock values, delete them.
1915 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1916 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1917 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001918 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001919 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001920 delete I->second.first;
1921 I->second.first = 0;
1922 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001923
Chris Lattnerdf986172009-01-02 07:01:27 +00001924 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1925 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1926 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001927 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001928 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001929 delete I->second.first;
1930 I->second.first = 0;
1931 }
1932}
1933
Chris Lattner09d9ef42009-10-28 03:39:23 +00001934bool LLParser::PerFunctionState::FinishFunction() {
1935 // Check to see if someone took the address of labels in this block.
1936 if (!P.ForwardRefBlockAddresses.empty()) {
1937 ValID FunctionID;
1938 if (!F.getName().empty()) {
1939 FunctionID.Kind = ValID::t_GlobalName;
1940 FunctionID.StrVal = F.getName();
1941 } else {
1942 FunctionID.Kind = ValID::t_GlobalID;
1943 FunctionID.UIntVal = FunctionNumber;
1944 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001945
Chris Lattner09d9ef42009-10-28 03:39:23 +00001946 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1947 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1948 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1949 // Resolve all these references.
1950 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1951 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001952
Chris Lattner09d9ef42009-10-28 03:39:23 +00001953 P.ForwardRefBlockAddresses.erase(FRBAI);
1954 }
1955 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001956
Chris Lattnerdf986172009-01-02 07:01:27 +00001957 if (!ForwardRefVals.empty())
1958 return P.Error(ForwardRefVals.begin()->second.second,
1959 "use of undefined value '%" + ForwardRefVals.begin()->first +
1960 "'");
1961 if (!ForwardRefValIDs.empty())
1962 return P.Error(ForwardRefValIDs.begin()->second.second,
1963 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001964 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001965 return false;
1966}
1967
1968
1969/// GetVal - Get a value with the specified name or ID, creating a
1970/// forward reference record if needed. This can return null if the value
1971/// exists but does not have the right type.
1972Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001973 Type *Ty, LocTy Loc) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001974 // Look this name up in the normal function symbol table.
1975 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001976
Chris Lattnerdf986172009-01-02 07:01:27 +00001977 // If this is a forward reference for the value, see if we already created a
1978 // forward ref record.
1979 if (Val == 0) {
1980 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1981 I = ForwardRefVals.find(Name);
1982 if (I != ForwardRefVals.end())
1983 Val = I->second.first;
1984 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001985
Chris Lattnerdf986172009-01-02 07:01:27 +00001986 // If we have the value in the symbol table or fwd-ref table, return it.
1987 if (Val) {
1988 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001989 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001990 P.Error(Loc, "'%" + Name + "' is not a basic block");
1991 else
1992 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001993 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001994 return 0;
1995 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001996
Chris Lattnerdf986172009-01-02 07:01:27 +00001997 // Don't make placeholders with invalid type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001998 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001999 P.Error(Loc, "invalid use of a non-first-class type");
2000 return 0;
2001 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002002
Chris Lattnerdf986172009-01-02 07:01:27 +00002003 // Otherwise, create a new forward reference for this value and remember it.
2004 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002005 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00002006 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00002007 else
2008 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002009
Chris Lattnerdf986172009-01-02 07:01:27 +00002010 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2011 return FwdVal;
2012}
2013
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002014Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +00002015 LocTy Loc) {
2016 // Look this name up in the normal function symbol table.
2017 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002018
Chris Lattnerdf986172009-01-02 07:01:27 +00002019 // If this is a forward reference for the value, see if we already created a
2020 // forward ref record.
2021 if (Val == 0) {
2022 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2023 I = ForwardRefValIDs.find(ID);
2024 if (I != ForwardRefValIDs.end())
2025 Val = I->second.first;
2026 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002027
Chris Lattnerdf986172009-01-02 07:01:27 +00002028 // If we have the value in the symbol table or fwd-ref table, return it.
2029 if (Val) {
2030 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002031 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002032 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002033 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002034 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002035 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002036 return 0;
2037 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002038
Chris Lattner1afcace2011-07-09 17:41:24 +00002039 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002040 P.Error(Loc, "invalid use of a non-first-class type");
2041 return 0;
2042 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002043
Chris Lattnerdf986172009-01-02 07:01:27 +00002044 // Otherwise, create a new forward reference for this value and remember it.
2045 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002046 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00002047 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00002048 else
2049 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002050
Chris Lattnerdf986172009-01-02 07:01:27 +00002051 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2052 return FwdVal;
2053}
2054
2055/// SetInstName - After an instruction is parsed and inserted into its
2056/// basic block, this installs its name.
2057bool LLParser::PerFunctionState::SetInstName(int NameID,
2058 const std::string &NameStr,
2059 LocTy NameLoc, Instruction *Inst) {
2060 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002061 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002062 if (NameID != -1 || !NameStr.empty())
2063 return P.Error(NameLoc, "instructions returning void cannot have a name");
2064 return false;
2065 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002066
Chris Lattnerdf986172009-01-02 07:01:27 +00002067 // If this was a numbered instruction, verify that the instruction is the
2068 // expected value and resolve any forward references.
2069 if (NameStr.empty()) {
2070 // If neither a name nor an ID was specified, just use the next ID.
2071 if (NameID == -1)
2072 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002073
Chris Lattnerdf986172009-01-02 07:01:27 +00002074 if (unsigned(NameID) != NumberedVals.size())
2075 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002076 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002077
Chris Lattnerdf986172009-01-02 07:01:27 +00002078 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2079 ForwardRefValIDs.find(NameID);
2080 if (FI != ForwardRefValIDs.end()) {
2081 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002082 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002083 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002084 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00002085 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00002086 ForwardRefValIDs.erase(FI);
2087 }
2088
2089 NumberedVals.push_back(Inst);
2090 return false;
2091 }
2092
2093 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2094 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2095 FI = ForwardRefVals.find(NameStr);
2096 if (FI != ForwardRefVals.end()) {
2097 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002098 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002099 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002100 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00002101 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00002102 ForwardRefVals.erase(FI);
2103 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002104
Chris Lattnerdf986172009-01-02 07:01:27 +00002105 // Set the name on the instruction.
2106 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002107
Benjamin Krameraf812352010-10-16 11:28:23 +00002108 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00002109 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00002110 NameStr + "'");
2111 return false;
2112}
2113
2114/// GetBB - Get a basic block with the specified name or ID, creating a
2115/// forward reference record if needed.
2116BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2117 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002118 return cast_or_null<BasicBlock>(GetVal(Name,
2119 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00002120}
2121
2122BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002123 return cast_or_null<BasicBlock>(GetVal(ID,
2124 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00002125}
2126
2127/// DefineBB - Define the specified basic block, which is either named or
2128/// unnamed. If there is an error, this returns null otherwise it returns
2129/// the block being defined.
2130BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2131 LocTy Loc) {
2132 BasicBlock *BB;
2133 if (Name.empty())
2134 BB = GetBB(NumberedVals.size(), Loc);
2135 else
2136 BB = GetBB(Name, Loc);
2137 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002138
Chris Lattnerdf986172009-01-02 07:01:27 +00002139 // Move the block to the end of the function. Forward ref'd blocks are
2140 // inserted wherever they happen to be referenced.
2141 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002142
Chris Lattnerdf986172009-01-02 07:01:27 +00002143 // Remove the block from forward ref sets.
2144 if (Name.empty()) {
2145 ForwardRefValIDs.erase(NumberedVals.size());
2146 NumberedVals.push_back(BB);
2147 } else {
2148 // BB forward references are already in the function symbol table.
2149 ForwardRefVals.erase(Name);
2150 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002151
Chris Lattnerdf986172009-01-02 07:01:27 +00002152 return BB;
2153}
2154
2155//===----------------------------------------------------------------------===//
2156// Constants.
2157//===----------------------------------------------------------------------===//
2158
2159/// ParseValID - Parse an abstract value that doesn't necessarily have a
2160/// type implied. For example, if we parse "4" we don't know what integer type
2161/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00002162/// sanity. PFS is used to convert function-local operands of metadata (since
2163/// metadata operands are not just parsed here but also converted to values).
2164/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00002165bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002166 ID.Loc = Lex.getLoc();
2167 switch (Lex.getKind()) {
2168 default: return TokError("expected value token");
2169 case lltok::GlobalID: // @42
2170 ID.UIntVal = Lex.getUIntVal();
2171 ID.Kind = ValID::t_GlobalID;
2172 break;
2173 case lltok::GlobalVar: // @foo
2174 ID.StrVal = Lex.getStrVal();
2175 ID.Kind = ValID::t_GlobalName;
2176 break;
2177 case lltok::LocalVarID: // %42
2178 ID.UIntVal = Lex.getUIntVal();
2179 ID.Kind = ValID::t_LocalID;
2180 break;
2181 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00002182 ID.StrVal = Lex.getStrVal();
2183 ID.Kind = ValID::t_LocalName;
2184 break;
Dan Gohman83448032010-07-14 18:26:50 +00002185 case lltok::exclaim: // !42, !{...}, or !"foo"
2186 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002187 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002188 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002189 ID.Kind = ValID::t_APSInt;
2190 break;
2191 case lltok::APFloat:
2192 ID.APFloatVal = Lex.getAPFloatVal();
2193 ID.Kind = ValID::t_APFloat;
2194 break;
2195 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002196 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002197 ID.Kind = ValID::t_Constant;
2198 break;
2199 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002200 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002201 ID.Kind = ValID::t_Constant;
2202 break;
2203 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2204 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2205 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002206
Chris Lattnerdf986172009-01-02 07:01:27 +00002207 case lltok::lbrace: {
2208 // ValID ::= '{' ConstVector '}'
2209 Lex.Lex();
2210 SmallVector<Constant*, 16> Elts;
2211 if (ParseGlobalValueVector(Elts) ||
2212 ParseToken(lltok::rbrace, "expected end of struct constant"))
2213 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002214
Chris Lattner1afcace2011-07-09 17:41:24 +00002215 ID.ConstantStructElts = new Constant*[Elts.size()];
2216 ID.UIntVal = Elts.size();
2217 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2218 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002219 return false;
2220 }
2221 case lltok::less: {
2222 // ValID ::= '<' ConstVector '>' --> Vector.
2223 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2224 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002225 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002226
Chris Lattnerdf986172009-01-02 07:01:27 +00002227 SmallVector<Constant*, 16> Elts;
2228 LocTy FirstEltLoc = Lex.getLoc();
2229 if (ParseGlobalValueVector(Elts) ||
2230 (isPackedStruct &&
2231 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2232 ParseToken(lltok::greater, "expected end of constant"))
2233 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002234
Chris Lattnerdf986172009-01-02 07:01:27 +00002235 if (isPackedStruct) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002236 ID.ConstantStructElts = new Constant*[Elts.size()];
2237 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2238 ID.UIntVal = Elts.size();
2239 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002240 return false;
2241 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002242
Chris Lattnerdf986172009-01-02 07:01:27 +00002243 if (Elts.empty())
2244 return Error(ID.Loc, "constant vector must not be empty");
2245
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002246 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002247 !Elts[0]->getType()->isFloatingPointTy() &&
2248 !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002249 return Error(FirstEltLoc,
Nadav Rotem16087692011-12-05 06:29:09 +00002250 "vector elements must have integer, pointer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002251
Chris Lattnerdf986172009-01-02 07:01:27 +00002252 // Verify that all the vector elements have the same type.
2253 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2254 if (Elts[i]->getType() != Elts[0]->getType())
2255 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002256 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002257 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002258
Chris Lattner2ca5c862011-02-15 00:14:00 +00002259 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002260 ID.Kind = ValID::t_Constant;
2261 return false;
2262 }
2263 case lltok::lsquare: { // Array Constant
2264 Lex.Lex();
2265 SmallVector<Constant*, 16> Elts;
2266 LocTy FirstEltLoc = Lex.getLoc();
2267 if (ParseGlobalValueVector(Elts) ||
2268 ParseToken(lltok::rsquare, "expected end of array constant"))
2269 return true;
2270
2271 // Handle empty element.
2272 if (Elts.empty()) {
2273 // Use undef instead of an array because it's inconvenient to determine
2274 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002275 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002276 return false;
2277 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002278
Chris Lattnerdf986172009-01-02 07:01:27 +00002279 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002280 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002281 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002282
Owen Andersondebcb012009-07-29 22:17:13 +00002283 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002284
Chris Lattnerdf986172009-01-02 07:01:27 +00002285 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002286 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002287 if (Elts[i]->getType() != Elts[0]->getType())
2288 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002289 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002290 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00002291 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002292
Jay Foad26701082011-06-22 09:24:39 +00002293 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002294 ID.Kind = ValID::t_Constant;
2295 return false;
2296 }
2297 case lltok::kw_c: // c "foo"
2298 Lex.Lex();
Chris Lattner18c7f802012-02-05 02:29:43 +00002299 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2300 false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002301 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2302 ID.Kind = ValID::t_Constant;
2303 return false;
2304
2305 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002306 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
Chad Rosier581600b2012-09-05 19:00:49 +00002307 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerdf986172009-01-02 07:01:27 +00002308 Lex.Lex();
2309 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002310 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosier581600b2012-09-05 19:00:49 +00002311 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002312 ParseStringConstant(ID.StrVal) ||
2313 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002314 ParseToken(lltok::StringConstant, "expected constraint string"))
2315 return true;
2316 ID.StrVal2 = Lex.getStrVal();
Chad Rosier36547342012-09-05 00:08:17 +00002317 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosier581600b2012-09-05 19:00:49 +00002318 (unsigned(AsmDialect)<<2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002319 ID.Kind = ValID::t_InlineAsm;
2320 return false;
2321 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002322
Chris Lattner09d9ef42009-10-28 03:39:23 +00002323 case lltok::kw_blockaddress: {
2324 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2325 Lex.Lex();
2326
2327 ValID Fn, Label;
2328 LocTy FnLoc, LabelLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00002329
Chris Lattner09d9ef42009-10-28 03:39:23 +00002330 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2331 ParseValID(Fn) ||
2332 ParseToken(lltok::comma, "expected comma in block address expression")||
2333 ParseValID(Label) ||
2334 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2335 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00002336
Chris Lattner09d9ef42009-10-28 03:39:23 +00002337 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2338 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002339 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002340 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman407a6162012-11-15 22:34:00 +00002341
Chris Lattner09d9ef42009-10-28 03:39:23 +00002342 // Make a global variable as a placeholder for this reference.
2343 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2344 false, GlobalValue::InternalLinkage,
2345 0, "");
2346 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2347 ID.ConstantVal = FwdRef;
2348 ID.Kind = ValID::t_Constant;
2349 return false;
2350 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002351
Chris Lattnerdf986172009-01-02 07:01:27 +00002352 case lltok::kw_trunc:
2353 case lltok::kw_zext:
2354 case lltok::kw_sext:
2355 case lltok::kw_fptrunc:
2356 case lltok::kw_fpext:
2357 case lltok::kw_bitcast:
2358 case lltok::kw_uitofp:
2359 case lltok::kw_sitofp:
2360 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002361 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002362 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002363 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002364 unsigned Opc = Lex.getUIntVal();
Chris Lattner1afcace2011-07-09 17:41:24 +00002365 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002366 Constant *SrcVal;
2367 Lex.Lex();
2368 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2369 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002370 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002371 ParseType(DestTy) ||
2372 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2373 return true;
2374 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2375 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002376 getTypeString(SrcVal->getType()) + "' to '" +
2377 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002378 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002379 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002380 ID.Kind = ValID::t_Constant;
2381 return false;
2382 }
2383 case lltok::kw_extractvalue: {
2384 Lex.Lex();
2385 Constant *Val;
2386 SmallVector<unsigned, 4> Indices;
2387 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2388 ParseGlobalTypeAndValue(Val) ||
2389 ParseIndexList(Indices) ||
2390 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2391 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002392
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002393 if (!Val->getType()->isAggregateType())
2394 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002395 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002396 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002397 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002398 ID.Kind = ValID::t_Constant;
2399 return false;
2400 }
2401 case lltok::kw_insertvalue: {
2402 Lex.Lex();
2403 Constant *Val0, *Val1;
2404 SmallVector<unsigned, 4> Indices;
2405 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2406 ParseGlobalTypeAndValue(Val0) ||
2407 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2408 ParseGlobalTypeAndValue(Val1) ||
2409 ParseIndexList(Indices) ||
2410 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2411 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002412 if (!Val0->getType()->isAggregateType())
2413 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002414 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002415 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002416 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002417 ID.Kind = ValID::t_Constant;
2418 return false;
2419 }
2420 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002421 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002422 unsigned PredVal, Opc = Lex.getUIntVal();
2423 Constant *Val0, *Val1;
2424 Lex.Lex();
2425 if (ParseCmpPredicate(PredVal, Opc) ||
2426 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2427 ParseGlobalTypeAndValue(Val0) ||
2428 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2429 ParseGlobalTypeAndValue(Val1) ||
2430 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2431 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002432
Chris Lattnerdf986172009-01-02 07:01:27 +00002433 if (Val0->getType() != Val1->getType())
2434 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002435
Chris Lattnerdf986172009-01-02 07:01:27 +00002436 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002437
Chris Lattnerdf986172009-01-02 07:01:27 +00002438 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002439 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002440 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002441 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002442 } else {
2443 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002444 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002445 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002446 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002447 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002448 }
2449 ID.Kind = ValID::t_Constant;
2450 return false;
2451 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002452
Chris Lattnerdf986172009-01-02 07:01:27 +00002453 // Binary Operators.
2454 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002455 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002456 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002457 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002458 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002459 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002460 case lltok::kw_udiv:
2461 case lltok::kw_sdiv:
2462 case lltok::kw_fdiv:
2463 case lltok::kw_urem:
2464 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002465 case lltok::kw_frem:
2466 case lltok::kw_shl:
2467 case lltok::kw_lshr:
2468 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002469 bool NUW = false;
2470 bool NSW = false;
2471 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002472 unsigned Opc = Lex.getUIntVal();
2473 Constant *Val0, *Val1;
2474 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002475 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002476 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2477 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002478 if (EatIfPresent(lltok::kw_nuw))
2479 NUW = true;
2480 if (EatIfPresent(lltok::kw_nsw)) {
2481 NSW = true;
2482 if (EatIfPresent(lltok::kw_nuw))
2483 NUW = true;
2484 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002485 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2486 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002487 if (EatIfPresent(lltok::kw_exact))
2488 Exact = true;
2489 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002490 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2491 ParseGlobalTypeAndValue(Val0) ||
2492 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2493 ParseGlobalTypeAndValue(Val1) ||
2494 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2495 return true;
2496 if (Val0->getType() != Val1->getType())
2497 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002498 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002499 if (NUW)
2500 return Error(ModifierLoc, "nuw only applies to integer operations");
2501 if (NSW)
2502 return Error(ModifierLoc, "nsw only applies to integer operations");
2503 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002504 // Check that the type is valid for the operator.
2505 switch (Opc) {
2506 case Instruction::Add:
2507 case Instruction::Sub:
2508 case Instruction::Mul:
2509 case Instruction::UDiv:
2510 case Instruction::SDiv:
2511 case Instruction::URem:
2512 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002513 case Instruction::Shl:
2514 case Instruction::AShr:
2515 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002516 if (!Val0->getType()->isIntOrIntVectorTy())
2517 return Error(ID.Loc, "constexpr requires integer operands");
2518 break;
2519 case Instruction::FAdd:
2520 case Instruction::FSub:
2521 case Instruction::FMul:
2522 case Instruction::FDiv:
2523 case Instruction::FRem:
2524 if (!Val0->getType()->isFPOrFPVectorTy())
2525 return Error(ID.Loc, "constexpr requires fp operands");
2526 break;
2527 default: llvm_unreachable("Unknown binary operator!");
2528 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002529 unsigned Flags = 0;
2530 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2531 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002532 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002533 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002534 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002535 ID.Kind = ValID::t_Constant;
2536 return false;
2537 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002538
Chris Lattnerdf986172009-01-02 07:01:27 +00002539 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002540 case lltok::kw_and:
2541 case lltok::kw_or:
2542 case lltok::kw_xor: {
2543 unsigned Opc = Lex.getUIntVal();
2544 Constant *Val0, *Val1;
2545 Lex.Lex();
2546 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2547 ParseGlobalTypeAndValue(Val0) ||
2548 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2549 ParseGlobalTypeAndValue(Val1) ||
2550 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2551 return true;
2552 if (Val0->getType() != Val1->getType())
2553 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002554 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002555 return Error(ID.Loc,
2556 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002557 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002558 ID.Kind = ValID::t_Constant;
2559 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002560 }
2561
Chris Lattnerdf986172009-01-02 07:01:27 +00002562 case lltok::kw_getelementptr:
2563 case lltok::kw_shufflevector:
2564 case lltok::kw_insertelement:
2565 case lltok::kw_extractelement:
2566 case lltok::kw_select: {
2567 unsigned Opc = Lex.getUIntVal();
2568 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002569 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002570 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002571 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002572 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002573 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2574 ParseGlobalValueVector(Elts) ||
2575 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2576 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002577
Chris Lattnerdf986172009-01-02 07:01:27 +00002578 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem16087692011-12-05 06:29:09 +00002579 if (Elts.size() == 0 ||
2580 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002581 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002582
Jay Foaddab3d292011-07-21 14:31:17 +00002583 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foada9203102011-07-25 09:48:08 +00002584 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002585 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad4b5e2072011-07-21 15:15:37 +00002586 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2587 InBounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002588 } else if (Opc == Instruction::Select) {
2589 if (Elts.size() != 3)
2590 return Error(ID.Loc, "expected three operands to select");
2591 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2592 Elts[2]))
2593 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002594 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002595 } else if (Opc == Instruction::ShuffleVector) {
2596 if (Elts.size() != 3)
2597 return Error(ID.Loc, "expected three operands to shufflevector");
2598 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2599 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002600 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002601 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002602 } else if (Opc == Instruction::ExtractElement) {
2603 if (Elts.size() != 2)
2604 return Error(ID.Loc, "expected two operands to extractelement");
2605 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2606 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002607 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002608 } else {
2609 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2610 if (Elts.size() != 3)
2611 return Error(ID.Loc, "expected three operands to insertelement");
2612 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2613 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002614 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002615 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002616 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002617
Chris Lattnerdf986172009-01-02 07:01:27 +00002618 ID.Kind = ValID::t_Constant;
2619 return false;
2620 }
2621 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002622
Chris Lattnerdf986172009-01-02 07:01:27 +00002623 Lex.Lex();
2624 return false;
2625}
2626
2627/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002628bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez92f238d2010-01-11 22:31:58 +00002629 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002630 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002631 Value *V = NULL;
2632 bool Parsed = ParseValID(ID) ||
2633 ConvertValIDToValue(Ty, ID, V, NULL);
2634 if (V && !(C = dyn_cast<Constant>(V)))
2635 return Error(ID.Loc, "global values must be constants");
2636 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002637}
2638
Victor Hernandez92f238d2010-01-11 22:31:58 +00002639bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002640 Type *Ty = 0;
2641 return ParseType(Ty) ||
2642 ParseGlobalValue(Ty, V);
Victor Hernandez92f238d2010-01-11 22:31:58 +00002643}
2644
2645/// ParseGlobalValueVector
2646/// ::= /*empty*/
2647/// ::= TypeAndValue (',' TypeAndValue)*
2648bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2649 // Empty list.
2650 if (Lex.getKind() == lltok::rbrace ||
2651 Lex.getKind() == lltok::rsquare ||
2652 Lex.getKind() == lltok::greater ||
2653 Lex.getKind() == lltok::rparen)
2654 return false;
2655
2656 Constant *C;
2657 if (ParseGlobalTypeAndValue(C)) return true;
2658 Elts.push_back(C);
2659
2660 while (EatIfPresent(lltok::comma)) {
2661 if (ParseGlobalTypeAndValue(C)) return true;
2662 Elts.push_back(C);
2663 }
2664
2665 return false;
2666}
2667
Dan Gohman309b3af2010-08-24 02:24:03 +00002668bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2669 assert(Lex.getKind() == lltok::lbrace);
2670 Lex.Lex();
2671
2672 SmallVector<Value*, 16> Elts;
2673 if (ParseMDNodeVector(Elts, PFS) ||
2674 ParseToken(lltok::rbrace, "expected end of metadata node"))
2675 return true;
2676
Jay Foadec9186b2011-04-21 19:59:31 +00002677 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002678 ID.Kind = ValID::t_MDNode;
2679 return false;
2680}
2681
Dan Gohman83448032010-07-14 18:26:50 +00002682/// ParseMetadataValue
2683/// ::= !42
2684/// ::= !{...}
2685/// ::= !"string"
2686bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2687 assert(Lex.getKind() == lltok::exclaim);
2688 Lex.Lex();
2689
2690 // MDNode:
2691 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002692 if (Lex.getKind() == lltok::lbrace)
2693 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002694
2695 // Standalone metadata reference
2696 // !42
2697 if (Lex.getKind() == lltok::APSInt) {
2698 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2699 ID.Kind = ValID::t_MDNode;
2700 return false;
2701 }
2702
2703 // MDString:
2704 // ::= '!' STRINGCONSTANT
2705 if (ParseMDString(ID.MDStringVal)) return true;
2706 ID.Kind = ValID::t_MDString;
2707 return false;
2708}
2709
Victor Hernandez92f238d2010-01-11 22:31:58 +00002710
2711//===----------------------------------------------------------------------===//
2712// Function Parsing.
2713//===----------------------------------------------------------------------===//
2714
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002715bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez92f238d2010-01-11 22:31:58 +00002716 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002717 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002718 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002719
Chris Lattnerdf986172009-01-02 07:01:27 +00002720 switch (ID.Kind) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002721 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002722 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2723 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2724 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002725 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002726 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2727 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2728 return (V == 0);
2729 case ValID::t_InlineAsm: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002730 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman407a6162012-11-15 22:34:00 +00002731 FunctionType *FTy =
Victor Hernandez92f238d2010-01-11 22:31:58 +00002732 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2733 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2734 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosier36547342012-09-05 00:08:17 +00002735 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosier581600b2012-09-05 19:00:49 +00002736 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez92f238d2010-01-11 22:31:58 +00002737 return false;
2738 }
2739 case ValID::t_MDNode:
2740 if (!Ty->isMetadataTy())
2741 return Error(ID.Loc, "metadata value must have metadata type");
2742 V = ID.MDNodeVal;
2743 return false;
2744 case ValID::t_MDString:
2745 if (!Ty->isMetadataTy())
2746 return Error(ID.Loc, "metadata value must have metadata type");
2747 V = ID.MDStringVal;
2748 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002749 case ValID::t_GlobalName:
2750 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2751 return V == 0;
2752 case ValID::t_GlobalID:
2753 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2754 return V == 0;
2755 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002756 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002757 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002758 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002759 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002760 return false;
2761 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002762 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002763 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2764 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002765
Dan Gohmance163392011-12-17 00:04:22 +00002766 // The lexer has no type info, so builds all half, float, and double FP
2767 // constants as double. Fix this here. Long double does not need this.
2768 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002769 bool Ignored;
Dan Gohmance163392011-12-17 00:04:22 +00002770 if (Ty->isHalfTy())
2771 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2772 &Ignored);
2773 else if (Ty->isFloatTy())
2774 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2775 &Ignored);
Chris Lattnerdf986172009-01-02 07:01:27 +00002776 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002777 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002778
Chris Lattner959873d2009-01-05 18:24:23 +00002779 if (V->getType() != Ty)
2780 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002781 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002782
Chris Lattnerdf986172009-01-02 07:01:27 +00002783 return false;
2784 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002785 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002786 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002787 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002788 return false;
2789 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002790 // FIXME: LabelTy should not be a first-class type.
Chris Lattner1afcace2011-07-09 17:41:24 +00002791 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002792 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002793 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002794 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002795 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002796 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002797 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002798 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002799 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002800 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002801 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002802 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002803 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002804 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002805 return false;
2806 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002807 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002808 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002809
Chris Lattnerdf986172009-01-02 07:01:27 +00002810 V = ID.ConstantVal;
2811 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +00002812 case ValID::t_ConstantStruct:
2813 case ValID::t_PackedConstantStruct:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002814 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002815 if (ST->getNumElements() != ID.UIntVal)
2816 return Error(ID.Loc,
2817 "initializer with struct type has wrong # elements");
2818 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2819 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman407a6162012-11-15 22:34:00 +00002820
Chris Lattner1afcace2011-07-09 17:41:24 +00002821 // Verify that the elements are compatible with the structtype.
2822 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2823 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2824 return Error(ID.Loc, "element " + Twine(i) +
2825 " of struct initializer doesn't match struct element type");
Michael Ilseman407a6162012-11-15 22:34:00 +00002826
Frits van Bommel39b5abf2011-07-18 12:00:32 +00002827 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2828 ID.UIntVal));
Chris Lattner1afcace2011-07-09 17:41:24 +00002829 } else
2830 return Error(ID.Loc, "constant expression type mismatch");
2831 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002832 }
Chandler Carruth732f05c2012-01-10 18:08:01 +00002833 llvm_unreachable("Invalid ValID");
Chris Lattnerdf986172009-01-02 07:01:27 +00002834}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002835
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002836bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002837 V = 0;
2838 ValID ID;
Chris Lattner1afcace2011-07-09 17:41:24 +00002839 return ParseValID(ID, PFS) ||
2840 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002841}
2842
Chris Lattner1afcace2011-07-09 17:41:24 +00002843bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2844 Type *Ty = 0;
2845 return ParseType(Ty) ||
2846 ParseValue(Ty, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002847}
2848
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002849bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2850 PerFunctionState &PFS) {
2851 Value *V;
2852 Loc = Lex.getLoc();
2853 if (ParseTypeAndValue(V, PFS)) return true;
2854 if (!isa<BasicBlock>(V))
2855 return Error(Loc, "expected a basic block");
2856 BB = cast<BasicBlock>(V);
2857 return false;
2858}
2859
2860
Chris Lattnerdf986172009-01-02 07:01:27 +00002861/// FunctionHeader
2862/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002863/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002864/// OptionalAlign OptGC
2865bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2866 // Parse the linkage.
2867 LocTy LinkageLoc = Lex.getLoc();
2868 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002869
Kostya Serebryany164b86b2012-01-20 17:56:17 +00002870 unsigned Visibility;
Bill Wendling702cc912012-10-15 20:35:56 +00002871 AttrBuilder RetAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002872 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00002873 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002874 LocTy RetTypeLoc = Lex.getLoc();
2875 if (ParseOptionalLinkage(Linkage) ||
2876 ParseOptionalVisibility(Visibility) ||
2877 ParseOptionalCallingConv(CC) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00002878 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002879 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002880 return true;
2881
2882 // Verify that the linkage is ok.
2883 switch ((GlobalValue::LinkageTypes)Linkage) {
2884 case GlobalValue::ExternalLinkage:
2885 break; // always ok.
2886 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002887 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002888 if (isDefine)
2889 return Error(LinkageLoc, "invalid linkage for function definition");
2890 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002891 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002892 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002893 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002894 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002895 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002896 case GlobalValue::LinkOnceAnyLinkage:
2897 case GlobalValue::LinkOnceODRLinkage:
Bill Wendling32811be2012-08-17 18:33:14 +00002898 case GlobalValue::LinkOnceODRAutoHideLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002899 case GlobalValue::WeakAnyLinkage:
2900 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002901 case GlobalValue::DLLExportLinkage:
2902 if (!isDefine)
2903 return Error(LinkageLoc, "invalid linkage for function declaration");
2904 break;
2905 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002906 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002907 return Error(LinkageLoc, "invalid function linkage type");
2908 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002909
Chris Lattner1afcace2011-07-09 17:41:24 +00002910 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002911 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002912
Chris Lattnerdf986172009-01-02 07:01:27 +00002913 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002914
2915 std::string FunctionName;
2916 if (Lex.getKind() == lltok::GlobalVar) {
2917 FunctionName = Lex.getStrVal();
2918 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2919 unsigned NameID = Lex.getUIntVal();
2920
2921 if (NameID != NumberedVals.size())
2922 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002923 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002924 } else {
2925 return TokError("expected function name");
2926 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002927
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002928 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002929
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002930 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002931 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002932
Chris Lattner1afcace2011-07-09 17:41:24 +00002933 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002934 bool isVarArg;
Bill Wendling702cc912012-10-15 20:35:56 +00002935 AttrBuilder FuncAttrs;
Bill Wendlingbaad55c2013-02-08 06:32:06 +00002936 std::vector<unsigned> FwdRefAttrGrps;
Chris Lattnerdf986172009-01-02 07:01:27 +00002937 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002938 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002939 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002940 bool UnnamedAddr;
2941 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002942
Chris Lattner1afcace2011-07-09 17:41:24 +00002943 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002944 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2945 &UnnamedAddrLoc) ||
Bill Wendlingbaad55c2013-02-08 06:32:06 +00002946 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002947 (EatIfPresent(lltok::kw_section) &&
2948 ParseStringConstant(Section)) ||
2949 ParseOptionalAlignment(Alignment) ||
2950 (EatIfPresent(lltok::kw_gc) &&
2951 ParseStringConstant(GC)))
2952 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002953
2954 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingf385f4c2012-10-08 23:27:46 +00002955 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendlingef99fe82012-09-21 15:26:31 +00002956 Alignment = FuncAttrs.getAlignment();
Bill Wendling034b94b2012-12-19 07:18:57 +00002957 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00002958 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002959
Chris Lattnerdf986172009-01-02 07:01:27 +00002960 // Okay, if we got here, the function is syntactically valid. Convert types
2961 // and do semantic checks.
Jay Foad5fdd6c82011-07-12 14:06:48 +00002962 std::vector<Type*> ParamTypeList;
Bill Wendlinga1683d62013-01-27 02:24:02 +00002963 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002964
Bill Wendlinge603fe42012-09-19 23:54:18 +00002965 if (RetAttrs.hasAttributes())
Bill Wendlinga1683d62013-01-27 02:24:02 +00002966 Attrs.push_back(AttributeSet::get(RetType->getContext(),
2967 AttributeSet::ReturnIndex,
2968 RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002969
Chris Lattnerdf986172009-01-02 07:01:27 +00002970 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002971 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendling73dee182013-01-31 00:29:54 +00002972 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
2973 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlinga1683d62013-01-27 02:24:02 +00002974 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
2975 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002976 }
2977
Bill Wendlinge603fe42012-09-19 23:54:18 +00002978 if (FuncAttrs.hasAttributes())
Bill Wendlinga1683d62013-01-27 02:24:02 +00002979 Attrs.push_back(AttributeSet::get(RetType->getContext(),
2980 AttributeSet::FunctionIndex,
2981 FuncAttrs));
Chris Lattnerdf986172009-01-02 07:01:27 +00002982
Bill Wendling99faa3b2012-12-07 23:16:57 +00002983 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002984
Bill Wendling94e94b32012-12-30 13:50:49 +00002985 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002986 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2987
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002988 FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002989 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002990 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002991
2992 Fn = 0;
2993 if (!FunctionName.empty()) {
2994 // If this was a definition of a forward reference, remove the definition
2995 // from the forward reference table and fill in the forward ref.
2996 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2997 ForwardRefVals.find(FunctionName);
2998 if (FRVI != ForwardRefVals.end()) {
2999 Fn = M->getFunction(FunctionName);
Nick Lewycky64ea2752012-10-11 00:38:25 +00003000 if (!Fn)
3001 return Error(FRVI->second.second, "invalid forward reference to "
3002 "function as global value!");
Chris Lattnerf1cfb952010-04-20 04:49:11 +00003003 if (Fn->getType() != PFT)
3004 return Error(FRVI->second.second, "invalid forward reference to "
3005 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman407a6162012-11-15 22:34:00 +00003006
Chris Lattnerdf986172009-01-02 07:01:27 +00003007 ForwardRefVals.erase(FRVI);
3008 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00003009 // Reject redefinitions.
3010 return Error(NameLoc, "invalid redefinition of function '" +
3011 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00003012 } else if (M->getNamedValue(FunctionName)) {
3013 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003014 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003015
Dan Gohman41905542009-08-29 23:37:49 +00003016 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00003017 // If this is a definition of a forward referenced function, make sure the
3018 // types agree.
3019 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3020 = ForwardRefValIDs.find(NumberedVals.size());
3021 if (I != ForwardRefValIDs.end()) {
3022 Fn = cast<Function>(I->second.first);
3023 if (Fn->getType() != PFT)
3024 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00003025 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00003026 ForwardRefValIDs.erase(I);
3027 }
3028 }
3029
3030 if (Fn == 0)
3031 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3032 else // Move the forward-reference to the correct spot in the module.
3033 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3034
3035 if (FunctionName.empty())
3036 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003037
Chris Lattnerdf986172009-01-02 07:01:27 +00003038 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3039 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3040 Fn->setCallingConv(CC);
3041 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00003042 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00003043 Fn->setAlignment(Alignment);
3044 Fn->setSection(Section);
3045 if (!GC.empty()) Fn->setGC(GC.c_str());
Bill Wendlingbaad55c2013-02-08 06:32:06 +00003046 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003047
Chris Lattnerdf986172009-01-02 07:01:27 +00003048 // Add all of the arguments we parsed to the function.
3049 Function::arg_iterator ArgIt = Fn->arg_begin();
3050 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3051 // If the argument has a name, insert it into the argument symbol table.
3052 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003053
Chris Lattnerdf986172009-01-02 07:01:27 +00003054 // Set the name, if it conflicted, it will be auto-renamed.
3055 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003056
Benjamin Krameraf812352010-10-16 11:28:23 +00003057 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00003058 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3059 ArgList[i].Name + "'");
3060 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003061
Chris Lattnerdf986172009-01-02 07:01:27 +00003062 return false;
3063}
3064
3065
3066/// ParseFunctionBody
3067/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00003068///
3069bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00003070 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00003071 return TokError("expected '{' in function body");
3072 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003073
Chris Lattner09d9ef42009-10-28 03:39:23 +00003074 int FunctionNumber = -1;
3075 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman407a6162012-11-15 22:34:00 +00003076
Chris Lattner09d9ef42009-10-28 03:39:23 +00003077 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003078
Chris Lattner2fdf8db2010-01-09 19:20:07 +00003079 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00003080 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00003081 return TokError("function body requires at least one basic block");
Michael Ilseman407a6162012-11-15 22:34:00 +00003082
Chris Lattner6b7c89e2011-06-17 06:42:57 +00003083 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00003084 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003085
Chris Lattnerdf986172009-01-02 07:01:27 +00003086 // Eat the }.
3087 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003088
Chris Lattnerdf986172009-01-02 07:01:27 +00003089 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00003090 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00003091}
3092
3093/// ParseBasicBlock
3094/// ::= LabelStr? Instruction*
3095bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3096 // If this basic block starts out with a name, remember it.
3097 std::string Name;
3098 LocTy NameLoc = Lex.getLoc();
3099 if (Lex.getKind() == lltok::LabelStr) {
3100 Name = Lex.getStrVal();
3101 Lex.Lex();
3102 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003103
Chris Lattnerdf986172009-01-02 07:01:27 +00003104 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3105 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003106
Chris Lattnerdf986172009-01-02 07:01:27 +00003107 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003108
Chris Lattnerdf986172009-01-02 07:01:27 +00003109 // Parse the instructions in this block until we get a terminator.
3110 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00003111 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00003112 do {
3113 // This instruction may have three possibilities for a name: a) none
3114 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3115 LocTy NameLoc = Lex.getLoc();
3116 int NameID = -1;
3117 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00003118
Chris Lattnerdf986172009-01-02 07:01:27 +00003119 if (Lex.getKind() == lltok::LocalVarID) {
3120 NameID = Lex.getUIntVal();
3121 Lex.Lex();
3122 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3123 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00003124 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003125 NameStr = Lex.getStrVal();
3126 Lex.Lex();
3127 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3128 return true;
3129 }
Devang Patelf633a062009-09-17 23:04:48 +00003130
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003131 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Topper85814382012-02-07 05:05:23 +00003132 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003133 case InstError: return true;
3134 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00003135 BB->getInstList().push_back(Inst);
3136
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003137 // With a normal result, we check to see if the instruction is followed by
3138 // a comma and metadata.
3139 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00003140 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003141 return true;
3142 break;
3143 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00003144 BB->getInstList().push_back(Inst);
3145
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003146 // If the instruction parser ate an extra comma at the end of it, it
3147 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00003148 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003149 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003150 break;
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003151 }
Devang Patelf633a062009-09-17 23:04:48 +00003152
Chris Lattnerdf986172009-01-02 07:01:27 +00003153 // Set the name on the instruction.
3154 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3155 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003156
Chris Lattnerdf986172009-01-02 07:01:27 +00003157 return false;
3158}
3159
3160//===----------------------------------------------------------------------===//
3161// Instruction Parsing.
3162//===----------------------------------------------------------------------===//
3163
3164/// ParseInstruction - Parse one of the many different instructions.
3165///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003166int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3167 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003168 lltok::Kind Token = Lex.getKind();
3169 if (Token == lltok::Eof)
3170 return TokError("found end of file when expecting more instructions");
3171 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003172 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00003173 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003174
Chris Lattnerdf986172009-01-02 07:01:27 +00003175 switch (Token) {
3176 default: return Error(Loc, "expected instruction opcode");
3177 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00003178 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003179 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3180 case lltok::kw_br: return ParseBr(Inst, PFS);
3181 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00003182 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003183 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003184 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003185 // Binary Operators.
3186 case lltok::kw_add:
3187 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00003188 case lltok::kw_mul:
3189 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00003190 bool NUW = EatIfPresent(lltok::kw_nuw);
3191 bool NSW = EatIfPresent(lltok::kw_nsw);
3192 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman407a6162012-11-15 22:34:00 +00003193
Chris Lattnerf067d582011-02-07 16:40:21 +00003194 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003195
Chris Lattnerf067d582011-02-07 16:40:21 +00003196 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3197 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3198 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00003199 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003200 case lltok::kw_fadd:
3201 case lltok::kw_fsub:
Michael Ilseman15c13d32012-11-27 00:42:44 +00003202 case lltok::kw_fmul:
3203 case lltok::kw_fdiv:
3204 case lltok::kw_frem: {
3205 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3206 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3207 if (Res != 0)
3208 return Res;
3209 if (FMF.any())
3210 Inst->setFastMathFlags(FMF);
3211 return 0;
3212 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003213
Chris Lattner35bda892011-02-06 21:44:57 +00003214 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00003215 case lltok::kw_udiv:
3216 case lltok::kw_lshr:
3217 case lltok::kw_ashr: {
3218 bool Exact = EatIfPresent(lltok::kw_exact);
3219
3220 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3221 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3222 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00003223 }
3224
Chris Lattnerdf986172009-01-02 07:01:27 +00003225 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003226 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003227 case lltok::kw_and:
3228 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003229 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003230 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003231 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 // Casts.
3233 case lltok::kw_trunc:
3234 case lltok::kw_zext:
3235 case lltok::kw_sext:
3236 case lltok::kw_fptrunc:
3237 case lltok::kw_fpext:
3238 case lltok::kw_bitcast:
3239 case lltok::kw_uitofp:
3240 case lltok::kw_sitofp:
3241 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003242 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003243 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003244 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003245 // Other.
3246 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003247 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003248 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3249 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3250 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3251 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlinge6e88262011-08-12 20:24:12 +00003252 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003253 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3254 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3255 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003256 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003257 case lltok::kw_load: return ParseLoad(Inst, PFS);
3258 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedmanf03bb262011-08-12 22:50:01 +00003259 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3260 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedman47f35132011-07-25 23:16:38 +00003261 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003262 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3263 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3264 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3265 }
3266}
3267
3268/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3269bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003270 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003271 switch (Lex.getKind()) {
David Tweedd80d6082013-01-07 13:32:38 +00003272 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerdf986172009-01-02 07:01:27 +00003273 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3274 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3275 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3276 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3277 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3278 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3279 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3280 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3281 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3282 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3283 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3284 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3285 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3286 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3287 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3288 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3289 }
3290 } else {
3291 switch (Lex.getKind()) {
David Tweedd80d6082013-01-07 13:32:38 +00003292 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerdf986172009-01-02 07:01:27 +00003293 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3294 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3295 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3296 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3297 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3298 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3299 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3300 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3301 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3302 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3303 }
3304 }
3305 Lex.Lex();
3306 return false;
3307}
3308
3309//===----------------------------------------------------------------------===//
3310// Terminator Instructions.
3311//===----------------------------------------------------------------------===//
3312
3313/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003314/// ::= 'ret' void (',' !dbg, !1)*
3315/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003316bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattner1afcace2011-07-09 17:41:24 +00003317 PerFunctionState &PFS) {
3318 SMLoc TypeLoc = Lex.getLoc();
3319 Type *Ty = 0;
Chris Lattnera9a9e072009-03-09 04:49:14 +00003320 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003321
Chris Lattner1afcace2011-07-09 17:41:24 +00003322 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman407a6162012-11-15 22:34:00 +00003323
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003324 if (Ty->isVoidTy()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003325 if (!ResType->isVoidTy())
3326 return Error(TypeLoc, "value doesn't match function result type '" +
3327 getTypeString(ResType) + "'");
Michael Ilseman407a6162012-11-15 22:34:00 +00003328
Owen Anderson1d0be152009-08-13 21:58:54 +00003329 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003330 return false;
3331 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003332
Chris Lattnerdf986172009-01-02 07:01:27 +00003333 Value *RV;
3334 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003335
Chris Lattner1afcace2011-07-09 17:41:24 +00003336 if (ResType != RV->getType())
3337 return Error(TypeLoc, "value doesn't match function result type '" +
3338 getTypeString(ResType) + "'");
Michael Ilseman407a6162012-11-15 22:34:00 +00003339
Owen Anderson1d0be152009-08-13 21:58:54 +00003340 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003341 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003342}
3343
3344
3345/// ParseBr
3346/// ::= 'br' TypeAndValue
3347/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3348bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3349 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003350 Value *Op0;
3351 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003352 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003353
Chris Lattnerdf986172009-01-02 07:01:27 +00003354 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3355 Inst = BranchInst::Create(BB);
3356 return false;
3357 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003358
Owen Anderson1d0be152009-08-13 21:58:54 +00003359 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003360 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003361
Chris Lattnerdf986172009-01-02 07:01:27 +00003362 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003363 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003364 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003365 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003366 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003367
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003368 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003369 return false;
3370}
3371
3372/// ParseSwitch
3373/// Instruction
3374/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3375/// JumpTable
3376/// ::= (TypeAndValue ',' TypeAndValue)*
3377bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3378 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003379 Value *Cond;
3380 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003381 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3382 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003383 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003384 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3385 return true;
3386
Duncan Sands1df98592010-02-16 11:11:14 +00003387 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003388 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003389
Chris Lattnerdf986172009-01-02 07:01:27 +00003390 // Parse the jump table pairs.
3391 SmallPtrSet<Value*, 32> SeenCases;
3392 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3393 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003394 Value *Constant;
3395 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003396
Chris Lattnerdf986172009-01-02 07:01:27 +00003397 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3398 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003399 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003400 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003401
Chris Lattnerdf986172009-01-02 07:01:27 +00003402 if (!SeenCases.insert(Constant))
3403 return Error(CondLoc, "duplicate case value in switch");
3404 if (!isa<ConstantInt>(Constant))
3405 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003406
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003407 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003408 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003409
Chris Lattnerdf986172009-01-02 07:01:27 +00003410 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003411
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003412 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003413 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3414 SI->addCase(Table[i].first, Table[i].second);
3415 Inst = SI;
3416 return false;
3417}
3418
Chris Lattnerab21db72009-10-28 00:19:10 +00003419/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003420/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003421/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3422bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003423 LocTy AddrLoc;
3424 Value *Address;
3425 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003426 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3427 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003428 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003429
Duncan Sands1df98592010-02-16 11:11:14 +00003430 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003431 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman407a6162012-11-15 22:34:00 +00003432
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003433 // Parse the destination list.
3434 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman407a6162012-11-15 22:34:00 +00003435
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003436 if (Lex.getKind() != lltok::rsquare) {
3437 BasicBlock *DestBB;
3438 if (ParseTypeAndBasicBlock(DestBB, PFS))
3439 return true;
3440 DestList.push_back(DestBB);
Michael Ilseman407a6162012-11-15 22:34:00 +00003441
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003442 while (EatIfPresent(lltok::comma)) {
3443 if (ParseTypeAndBasicBlock(DestBB, PFS))
3444 return true;
3445 DestList.push_back(DestBB);
3446 }
3447 }
Michael Ilseman407a6162012-11-15 22:34:00 +00003448
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003449 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3450 return true;
3451
Chris Lattnerab21db72009-10-28 00:19:10 +00003452 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003453 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3454 IBI->addDestination(DestList[i]);
3455 Inst = IBI;
3456 return false;
3457}
3458
3459
Chris Lattnerdf986172009-01-02 07:01:27 +00003460/// ParseInvoke
3461/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3462/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3463bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3464 LocTy CallLoc = Lex.getLoc();
Bill Wendling702cc912012-10-15 20:35:56 +00003465 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingbaad55c2013-02-08 06:32:06 +00003466 std::vector<unsigned> FwdRefAttrGrps;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003467 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003468 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003469 LocTy RetTypeLoc;
3470 ValID CalleeID;
3471 SmallVector<ParamInfo, 16> ArgList;
3472
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003473 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003474 if (ParseOptionalCallingConv(CC) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00003475 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003476 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003477 ParseValID(CalleeID) ||
3478 ParseParameterList(ArgList, PFS) ||
Bill Wendlingbaad55c2013-02-08 06:32:06 +00003479 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003480 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003481 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003482 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003483 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003484 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003485
Chris Lattnerdf986172009-01-02 07:01:27 +00003486 // If RetType is a non-function pointer type, then this is the short syntax
3487 // for the call, which means that RetType is just the return type. Infer the
3488 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003489 PointerType *PFTy = 0;
3490 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003491 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3492 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3493 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003494 std::vector<Type*> ParamTypes;
Chris Lattnerdf986172009-01-02 07:01:27 +00003495 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3496 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003497
Chris Lattnerdf986172009-01-02 07:01:27 +00003498 if (!FunctionType::isValidReturnType(RetType))
3499 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003500
Owen Andersondebcb012009-07-29 22:17:13 +00003501 Ty = FunctionType::get(RetType, ParamTypes, false);
3502 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003503 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003504
Chris Lattnerdf986172009-01-02 07:01:27 +00003505 // Look up the callee.
3506 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003507 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003508
Bill Wendling034b94b2012-12-19 07:18:57 +00003509 // Set up the Attribute for the function.
Bill Wendlinga1683d62013-01-27 02:24:02 +00003510 SmallVector<AttributeSet, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003511 if (RetAttrs.hasAttributes())
Bill Wendlinga1683d62013-01-27 02:24:02 +00003512 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3513 AttributeSet::ReturnIndex,
3514 RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003515
Chris Lattnerdf986172009-01-02 07:01:27 +00003516 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003517
Chris Lattnerdf986172009-01-02 07:01:27 +00003518 // Loop through FunctionType's arguments and ensure they are specified
3519 // correctly. Also, gather any parameter attributes.
3520 FunctionType::param_iterator I = Ty->param_begin();
3521 FunctionType::param_iterator E = Ty->param_end();
3522 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003523 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003524 if (I != E) {
3525 ExpectedTy = *I++;
3526 } else if (!Ty->isVarArg()) {
3527 return Error(ArgList[i].Loc, "too many arguments specified");
3528 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003529
Chris Lattnerdf986172009-01-02 07:01:27 +00003530 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3531 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003532 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003533 Args.push_back(ArgList[i].V);
Bill Wendling73dee182013-01-31 00:29:54 +00003534 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3535 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlinga1683d62013-01-27 02:24:02 +00003536 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3537 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003538 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003539
Chris Lattnerdf986172009-01-02 07:01:27 +00003540 if (I != E)
3541 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003542
Bill Wendlinge603fe42012-09-19 23:54:18 +00003543 if (FnAttrs.hasAttributes())
Bill Wendlinga1683d62013-01-27 02:24:02 +00003544 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3545 AttributeSet::FunctionIndex,
3546 FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003547
Bill Wendling034b94b2012-12-19 07:18:57 +00003548 // Finish off the Attribute and check them
Bill Wendling99faa3b2012-12-07 23:16:57 +00003549 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003550
Jay Foada3efbb12011-07-15 08:37:34 +00003551 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003552 II->setCallingConv(CC);
3553 II->setAttributes(PAL);
Bill Wendlingbaad55c2013-02-08 06:32:06 +00003554 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerdf986172009-01-02 07:01:27 +00003555 Inst = II;
3556 return false;
3557}
3558
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003559/// ParseResume
3560/// ::= 'resume' TypeAndValue
3561bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3562 Value *Exn; LocTy ExnLoc;
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003563 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3564 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003565
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003566 ResumeInst *RI = ResumeInst::Create(Exn);
3567 Inst = RI;
3568 return false;
3569}
Chris Lattnerdf986172009-01-02 07:01:27 +00003570
3571//===----------------------------------------------------------------------===//
3572// Binary Operators.
3573//===----------------------------------------------------------------------===//
3574
3575/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003576/// ::= ArithmeticOps TypeAndValue ',' Value
3577///
3578/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3579/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003580bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003581 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003582 LocTy Loc; Value *LHS, *RHS;
3583 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3584 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3585 ParseValue(LHS->getType(), RHS, PFS))
3586 return true;
3587
Chris Lattnere914b592009-01-05 08:24:46 +00003588 bool Valid;
3589 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003590 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003591 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003592 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3593 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003594 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003595 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3596 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003597 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003598
Chris Lattnere914b592009-01-05 08:24:46 +00003599 if (!Valid)
3600 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003601
Chris Lattnerdf986172009-01-02 07:01:27 +00003602 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3603 return false;
3604}
3605
3606/// ParseLogical
3607/// ::= ArithmeticOps TypeAndValue ',' Value {
3608bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3609 unsigned Opc) {
3610 LocTy Loc; Value *LHS, *RHS;
3611 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3612 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3613 ParseValue(LHS->getType(), RHS, PFS))
3614 return true;
3615
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003616 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003617 return Error(Loc,"instruction requires integer or integer vector operands");
3618
3619 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3620 return false;
3621}
3622
3623
3624/// ParseCompare
3625/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3626/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003627bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3628 unsigned Opc) {
3629 // Parse the integer/fp comparison predicate.
3630 LocTy Loc;
3631 unsigned Pred;
3632 Value *LHS, *RHS;
3633 if (ParseCmpPredicate(Pred, Opc) ||
3634 ParseTypeAndValue(LHS, Loc, PFS) ||
3635 ParseToken(lltok::comma, "expected ',' after compare value") ||
3636 ParseValue(LHS->getType(), RHS, PFS))
3637 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003638
Chris Lattnerdf986172009-01-02 07:01:27 +00003639 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003640 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003641 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003642 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003643 } else {
3644 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003645 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00003646 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003647 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003648 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003649 }
3650 return false;
3651}
3652
3653//===----------------------------------------------------------------------===//
3654// Other Instructions.
3655//===----------------------------------------------------------------------===//
3656
3657
3658/// ParseCast
3659/// ::= CastOpc TypeAndValue 'to' Type
3660bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3661 unsigned Opc) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003662 LocTy Loc;
3663 Value *Op;
3664 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003665 if (ParseTypeAndValue(Op, Loc, PFS) ||
3666 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3667 ParseType(DestTy))
3668 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003669
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003670 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3671 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003672 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003673 getTypeString(Op->getType()) + "' to '" +
3674 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003675 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003676 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3677 return false;
3678}
3679
3680/// ParseSelect
3681/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3682bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3683 LocTy Loc;
3684 Value *Op0, *Op1, *Op2;
3685 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3686 ParseToken(lltok::comma, "expected ',' after select condition") ||
3687 ParseTypeAndValue(Op1, PFS) ||
3688 ParseToken(lltok::comma, "expected ',' after select value") ||
3689 ParseTypeAndValue(Op2, PFS))
3690 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003691
Chris Lattnerdf986172009-01-02 07:01:27 +00003692 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3693 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003694
Chris Lattnerdf986172009-01-02 07:01:27 +00003695 Inst = SelectInst::Create(Op0, Op1, Op2);
3696 return false;
3697}
3698
Chris Lattner0088a5c2009-01-05 08:18:44 +00003699/// ParseVA_Arg
3700/// ::= 'va_arg' TypeAndValue ',' Type
3701bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003702 Value *Op;
Chris Lattner1afcace2011-07-09 17:41:24 +00003703 Type *EltTy = 0;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003704 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003705 if (ParseTypeAndValue(Op, PFS) ||
3706 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003707 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003708 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003709
Chris Lattner0088a5c2009-01-05 08:18:44 +00003710 if (!EltTy->isFirstClassType())
3711 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003712
3713 Inst = new VAArgInst(Op, EltTy);
3714 return false;
3715}
3716
3717/// ParseExtractElement
3718/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3719bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3720 LocTy Loc;
3721 Value *Op0, *Op1;
3722 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3723 ParseToken(lltok::comma, "expected ',' after extract value") ||
3724 ParseTypeAndValue(Op1, PFS))
3725 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003726
Chris Lattnerdf986172009-01-02 07:01:27 +00003727 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3728 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003729
Eric Christophera3500da2009-07-25 02:28:41 +00003730 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003731 return false;
3732}
3733
3734/// ParseInsertElement
3735/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3736bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3737 LocTy Loc;
3738 Value *Op0, *Op1, *Op2;
3739 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3740 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3741 ParseTypeAndValue(Op1, PFS) ||
3742 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3743 ParseTypeAndValue(Op2, PFS))
3744 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003745
Chris Lattnerdf986172009-01-02 07:01:27 +00003746 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003747 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003748
Chris Lattnerdf986172009-01-02 07:01:27 +00003749 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3750 return false;
3751}
3752
3753/// ParseShuffleVector
3754/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3755bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3756 LocTy Loc;
3757 Value *Op0, *Op1, *Op2;
3758 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3759 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3760 ParseTypeAndValue(Op1, PFS) ||
3761 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3762 ParseTypeAndValue(Op2, PFS))
3763 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003764
Chris Lattnerdf986172009-01-02 07:01:27 +00003765 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperaf393682012-02-01 23:43:12 +00003766 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003767
Chris Lattnerdf986172009-01-02 07:01:27 +00003768 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3769 return false;
3770}
3771
3772/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003773/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003774int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003775 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003776 Value *Op0, *Op1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003777
Chris Lattner1afcace2011-07-09 17:41:24 +00003778 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003779 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3780 ParseValue(Ty, Op0, PFS) ||
3781 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003782 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003783 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3784 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003785
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003786 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003787 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3788 while (1) {
3789 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003790
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003791 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003792 break;
3793
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003794 if (Lex.getKind() == lltok::MetadataVar) {
3795 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003796 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003797 }
Devang Patela43d46f2009-10-16 18:45:49 +00003798
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003799 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003800 ParseValue(Ty, Op0, PFS) ||
3801 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003802 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003803 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3804 return true;
3805 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003806
Chris Lattnerdf986172009-01-02 07:01:27 +00003807 if (!Ty->isFirstClassType())
3808 return Error(TypeLoc, "phi node must have first class type");
3809
Jay Foad3ecfc862011-03-30 11:28:46 +00003810 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003811 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3812 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3813 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003814 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003815}
3816
Bill Wendlinge6e88262011-08-12 20:24:12 +00003817/// ParseLandingPad
3818/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3819/// Clause
3820/// ::= 'catch' TypeAndValue
3821/// ::= 'filter'
3822/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3823bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3824 Type *Ty = 0; LocTy TyLoc;
3825 Value *PersFn; LocTy PersFnLoc;
Bill Wendlinge6e88262011-08-12 20:24:12 +00003826
3827 if (ParseType(Ty, TyLoc) ||
3828 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3829 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3830 return true;
3831
3832 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3833 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3834
3835 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3836 LandingPadInst::ClauseType CT;
3837 if (EatIfPresent(lltok::kw_catch))
3838 CT = LandingPadInst::Catch;
3839 else if (EatIfPresent(lltok::kw_filter))
3840 CT = LandingPadInst::Filter;
3841 else
3842 return TokError("expected 'catch' or 'filter' clause type");
3843
3844 Value *V; LocTy VLoc;
3845 if (ParseTypeAndValue(V, VLoc, PFS)) {
3846 delete LP;
3847 return true;
3848 }
3849
Bill Wendling746c8822011-08-12 20:52:25 +00003850 // A 'catch' type expects a non-array constant. A filter clause expects an
3851 // array constant.
3852 if (CT == LandingPadInst::Catch) {
3853 if (isa<ArrayType>(V->getType()))
3854 Error(VLoc, "'catch' clause has an invalid type");
3855 } else {
3856 if (!isa<ArrayType>(V->getType()))
3857 Error(VLoc, "'filter' clause has an invalid type");
3858 }
3859
Bill Wendlinge6e88262011-08-12 20:24:12 +00003860 LP->addClause(V);
3861 }
3862
3863 Inst = LP;
3864 return false;
3865}
3866
Chris Lattnerdf986172009-01-02 07:01:27 +00003867/// ParseCall
3868/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3869/// ParameterList OptionalAttrs
3870bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3871 bool isTail) {
Bill Wendling702cc912012-10-15 20:35:56 +00003872 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingbaad55c2013-02-08 06:32:06 +00003873 std::vector<unsigned> FwdRefAttrGrps;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003874 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003875 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003876 LocTy RetTypeLoc;
3877 ValID CalleeID;
3878 SmallVector<ParamInfo, 16> ArgList;
3879 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003880
Chris Lattnerdf986172009-01-02 07:01:27 +00003881 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3882 ParseOptionalCallingConv(CC) ||
Bill Wendlinge01b81b2012-12-04 23:40:58 +00003883 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003884 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003885 ParseValID(CalleeID) ||
3886 ParseParameterList(ArgList, PFS) ||
Bill Wendlingbaad55c2013-02-08 06:32:06 +00003887 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false))
Chris Lattnerdf986172009-01-02 07:01:27 +00003888 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003889
Chris Lattnerdf986172009-01-02 07:01:27 +00003890 // If RetType is a non-function pointer type, then this is the short syntax
3891 // for the call, which means that RetType is just the return type. Infer the
3892 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003893 PointerType *PFTy = 0;
3894 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003895 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3896 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3897 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003898 std::vector<Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003899 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3900 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003901
Chris Lattnerdf986172009-01-02 07:01:27 +00003902 if (!FunctionType::isValidReturnType(RetType))
3903 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003904
Owen Andersondebcb012009-07-29 22:17:13 +00003905 Ty = FunctionType::get(RetType, ParamTypes, false);
3906 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003907 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003908
Chris Lattnerdf986172009-01-02 07:01:27 +00003909 // Look up the callee.
3910 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003911 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003912
Bill Wendling034b94b2012-12-19 07:18:57 +00003913 // Set up the Attribute for the function.
Bill Wendlinga1683d62013-01-27 02:24:02 +00003914 SmallVector<AttributeSet, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003915 if (RetAttrs.hasAttributes())
Bill Wendlinga1683d62013-01-27 02:24:02 +00003916 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3917 AttributeSet::ReturnIndex,
3918 RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003919
Chris Lattnerdf986172009-01-02 07:01:27 +00003920 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003921
Chris Lattnerdf986172009-01-02 07:01:27 +00003922 // Loop through FunctionType's arguments and ensure they are specified
3923 // correctly. Also, gather any parameter attributes.
3924 FunctionType::param_iterator I = Ty->param_begin();
3925 FunctionType::param_iterator E = Ty->param_end();
3926 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003927 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003928 if (I != E) {
3929 ExpectedTy = *I++;
3930 } else if (!Ty->isVarArg()) {
3931 return Error(ArgList[i].Loc, "too many arguments specified");
3932 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003933
Chris Lattnerdf986172009-01-02 07:01:27 +00003934 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3935 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003936 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003937 Args.push_back(ArgList[i].V);
Bill Wendling73dee182013-01-31 00:29:54 +00003938 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3939 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlinga1683d62013-01-27 02:24:02 +00003940 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3941 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003942 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003943
Chris Lattnerdf986172009-01-02 07:01:27 +00003944 if (I != E)
3945 return Error(CallLoc, "not enough parameters specified for call");
3946
Bill Wendlinge603fe42012-09-19 23:54:18 +00003947 if (FnAttrs.hasAttributes())
Bill Wendlinga1683d62013-01-27 02:24:02 +00003948 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3949 AttributeSet::FunctionIndex,
3950 FnAttrs));
Chris Lattnerdf986172009-01-02 07:01:27 +00003951
Bill Wendling034b94b2012-12-19 07:18:57 +00003952 // Finish off the Attribute and check them
Bill Wendling99faa3b2012-12-07 23:16:57 +00003953 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003954
Jay Foada3efbb12011-07-15 08:37:34 +00003955 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003956 CI->setTailCall(isTail);
3957 CI->setCallingConv(CC);
3958 CI->setAttributes(PAL);
Bill Wendlingbaad55c2013-02-08 06:32:06 +00003959 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerdf986172009-01-02 07:01:27 +00003960 Inst = CI;
3961 return false;
3962}
3963
3964//===----------------------------------------------------------------------===//
3965// Memory Instructions.
3966//===----------------------------------------------------------------------===//
3967
3968/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003969/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003970int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003971 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003972 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003973 unsigned Alignment = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00003974 Type *Ty = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003975 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003976
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003977 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003978 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003979 if (Lex.getKind() == lltok::kw_align) {
3980 if (ParseOptionalAlignment(Alignment)) return true;
3981 } else if (Lex.getKind() == lltok::MetadataVar) {
3982 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003983 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003984 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3985 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3986 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003987 }
3988 }
3989
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003990 if (Size && !Size->getType()->isIntegerTy())
3991 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003992
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003993 Inst = new AllocaInst(Ty, Size, Alignment);
3994 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003995}
3996
3997/// ParseLoad
Eli Friedmanf03bb262011-08-12 22:50:01 +00003998/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman407a6162012-11-15 22:34:00 +00003999/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedmanf03bb262011-08-12 22:50:01 +00004000/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00004001int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004002 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00004003 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00004004 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00004005 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00004006 AtomicOrdering Ordering = NotAtomic;
4007 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00004008
4009 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00004010 isAtomic = true;
4011 Lex.Lex();
4012 }
4013
Chris Lattnerfbe910e2011-11-27 06:56:53 +00004014 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00004015 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00004016 isVolatile = true;
4017 Lex.Lex();
4018 }
4019
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00004020 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00004021 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00004022 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4023 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00004024
Duncan Sands1df98592010-02-16 11:11:14 +00004025 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00004026 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4027 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman21006d42011-08-09 23:02:53 +00004028 if (isAtomic && !Alignment)
4029 return Error(Loc, "atomic load must have explicit non-zero alignment");
4030 if (Ordering == Release || Ordering == AcquireRelease)
4031 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004032
Eli Friedman21006d42011-08-09 23:02:53 +00004033 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00004034 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004035}
4036
4037/// ParseStore
Eli Friedmanf03bb262011-08-12 22:50:01 +00004038
4039/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4040/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman21006d42011-08-09 23:02:53 +00004041/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00004042int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004043 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00004044 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00004045 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00004046 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00004047 AtomicOrdering Ordering = NotAtomic;
4048 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00004049
4050 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00004051 isAtomic = true;
4052 Lex.Lex();
4053 }
4054
Chris Lattnerfbe910e2011-11-27 06:56:53 +00004055 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00004056 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00004057 isVolatile = true;
4058 Lex.Lex();
4059 }
4060
Chris Lattnerdf986172009-01-02 07:01:27 +00004061 if (ParseTypeAndValue(Val, Loc, PFS) ||
4062 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00004063 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00004064 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00004065 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004066 return true;
Devang Patelf633a062009-09-17 23:04:48 +00004067
Duncan Sands1df98592010-02-16 11:11:14 +00004068 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00004069 return Error(PtrLoc, "store operand must be a pointer");
4070 if (!Val->getType()->isFirstClassType())
4071 return Error(Loc, "store operand must be a first class value");
4072 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4073 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman21006d42011-08-09 23:02:53 +00004074 if (isAtomic && !Alignment)
4075 return Error(Loc, "atomic store must have explicit non-zero alignment");
4076 if (Ordering == Acquire || Ordering == AcquireRelease)
4077 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004078
Eli Friedman21006d42011-08-09 23:02:53 +00004079 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00004080 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004081}
4082
Eli Friedmanff030482011-07-28 21:48:00 +00004083/// ParseCmpXchg
Eli Friedmanf03bb262011-08-12 22:50:01 +00004084/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4085/// 'singlethread'? AtomicOrdering
4086int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00004087 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4088 bool AteExtraComma = false;
4089 AtomicOrdering Ordering = NotAtomic;
4090 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00004091 bool isVolatile = false;
4092
4093 if (EatIfPresent(lltok::kw_volatile))
4094 isVolatile = true;
4095
Eli Friedmanff030482011-07-28 21:48:00 +00004096 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4097 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4098 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4099 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4100 ParseTypeAndValue(New, NewLoc, PFS) ||
4101 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4102 return true;
4103
4104 if (Ordering == Unordered)
4105 return TokError("cmpxchg cannot be unordered");
4106 if (!Ptr->getType()->isPointerTy())
4107 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4108 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4109 return Error(CmpLoc, "compare value and pointer type do not match");
4110 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4111 return Error(NewLoc, "new value and pointer type do not match");
4112 if (!New->getType()->isIntegerTy())
4113 return Error(NewLoc, "cmpxchg operand must be an integer");
4114 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4115 if (Size < 8 || (Size & (Size - 1)))
4116 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4117 " integer");
4118
4119 AtomicCmpXchgInst *CXI =
4120 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
4121 CXI->setVolatile(isVolatile);
4122 Inst = CXI;
4123 return AteExtraComma ? InstExtraComma : InstNormal;
4124}
4125
4126/// ParseAtomicRMW
Eli Friedmanf03bb262011-08-12 22:50:01 +00004127/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4128/// 'singlethread'? AtomicOrdering
4129int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00004130 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4131 bool AteExtraComma = false;
4132 AtomicOrdering Ordering = NotAtomic;
4133 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00004134 bool isVolatile = false;
Eli Friedmanff030482011-07-28 21:48:00 +00004135 AtomicRMWInst::BinOp Operation;
Eli Friedmanf03bb262011-08-12 22:50:01 +00004136
4137 if (EatIfPresent(lltok::kw_volatile))
4138 isVolatile = true;
4139
Eli Friedmanff030482011-07-28 21:48:00 +00004140 switch (Lex.getKind()) {
4141 default: return TokError("expected binary operation in atomicrmw");
4142 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4143 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4144 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4145 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4146 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4147 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4148 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4149 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4150 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4151 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4152 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4153 }
4154 Lex.Lex(); // Eat the operation.
4155
4156 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4157 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4158 ParseTypeAndValue(Val, ValLoc, PFS) ||
4159 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4160 return true;
4161
4162 if (Ordering == Unordered)
4163 return TokError("atomicrmw cannot be unordered");
4164 if (!Ptr->getType()->isPointerTy())
4165 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4166 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4167 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4168 if (!Val->getType()->isIntegerTy())
4169 return Error(ValLoc, "atomicrmw operand must be an integer");
4170 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4171 if (Size < 8 || (Size & (Size - 1)))
4172 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4173 " integer");
4174
4175 AtomicRMWInst *RMWI =
4176 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4177 RMWI->setVolatile(isVolatile);
4178 Inst = RMWI;
4179 return AteExtraComma ? InstExtraComma : InstNormal;
4180}
4181
Eli Friedman47f35132011-07-25 23:16:38 +00004182/// ParseFence
4183/// ::= 'fence' 'singlethread'? AtomicOrdering
4184int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4185 AtomicOrdering Ordering = NotAtomic;
4186 SynchronizationScope Scope = CrossThread;
4187 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4188 return true;
4189
4190 if (Ordering == Unordered)
4191 return TokError("fence cannot be unordered");
4192 if (Ordering == Monotonic)
4193 return TokError("fence cannot be monotonic");
4194
4195 Inst = new FenceInst(Context, Ordering, Scope);
4196 return InstNormal;
4197}
4198
Chris Lattnerdf986172009-01-02 07:01:27 +00004199/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00004200/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004201int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Nadav Rotem16087692011-12-05 06:29:09 +00004202 Value *Ptr = 0;
4203 Value *Val = 0;
4204 LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00004205
Dan Gohmandcb40a32009-07-29 15:58:36 +00004206 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00004207
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004208 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00004209
Nadav Rotem16087692011-12-05 06:29:09 +00004210 if (!Ptr->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00004211 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004212
Chris Lattnerdf986172009-01-02 07:01:27 +00004213 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004214 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004215 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004216 if (Lex.getKind() == lltok::MetadataVar) {
4217 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00004218 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004219 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004220 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem16087692011-12-05 06:29:09 +00004221 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00004222 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem16087692011-12-05 06:29:09 +00004223 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4224 return Error(EltLoc, "getelementptr index type missmatch");
4225 if (Val->getType()->isVectorTy()) {
4226 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4227 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4228 if (ValNumEl != PtrNumEl)
4229 return Error(EltLoc,
4230 "getelementptr vector index has a wrong number of elements");
4231 }
Chris Lattnerdf986172009-01-02 07:01:27 +00004232 Indices.push_back(Val);
4233 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00004234
Jay Foada9203102011-07-25 09:48:08 +00004235 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004236 return Error(Loc, "invalid getelementptr indices");
Jay Foada9203102011-07-25 09:48:08 +00004237 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohmandd8004d2009-07-27 21:53:46 +00004238 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004239 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004240 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004241}
4242
4243/// ParseExtractValue
4244/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004245int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004246 Value *Val; LocTy Loc;
4247 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004248 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004249 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004250 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004251 return true;
4252
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004253 if (!Val->getType()->isAggregateType())
4254 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00004255
Jay Foadfc6d3a42011-07-13 10:26:04 +00004256 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004257 return Error(Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004258 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004259 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004260}
4261
4262/// ParseInsertValue
4263/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004264int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004265 Value *Val0, *Val1; LocTy Loc0, Loc1;
4266 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004267 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004268 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4269 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4270 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004271 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004272 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00004273
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004274 if (!Val0->getType()->isAggregateType())
4275 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004276
Jay Foadfc6d3a42011-07-13 10:26:04 +00004277 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004278 return Error(Loc0, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004279 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004280 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004281}
Nick Lewycky21cc4462009-04-04 07:22:01 +00004282
4283//===----------------------------------------------------------------------===//
4284// Embedded metadata.
4285//===----------------------------------------------------------------------===//
4286
4287/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00004288/// ::= Element (',' Element)*
4289/// Element
4290/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00004291bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00004292 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00004293 // Check for an empty list.
4294 if (Lex.getKind() == lltok::rbrace)
4295 return false;
4296
Nick Lewycky21cc4462009-04-04 07:22:01 +00004297 do {
Chris Lattnera7352392009-12-30 04:42:57 +00004298 // Null is a special case since it is typeless.
4299 if (EatIfPresent(lltok::kw_null)) {
4300 Elts.push_back(0);
4301 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00004302 }
Michael Ilseman407a6162012-11-15 22:34:00 +00004303
Chris Lattnera7352392009-12-30 04:42:57 +00004304 Value *V = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00004305 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00004306 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004307 } while (EatIfPresent(lltok::comma));
4308
4309 return false;
4310}