blob: 66a8e17e119260b6ecc3f419501be2792f0e76fe [file] [log] [blame]
Chris Lattnerdf986172009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
15#include "llvm/AutoUpgrade.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instructions.h"
21#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000022#include "llvm/Operator.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000023#include "llvm/ValueSymbolTable.h"
24#include "llvm/ADT/SmallPtrSet.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;
55
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
58
59 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 }
67
68
Chris Lattner09d9ef42009-10-28 03:39:23 +000069 // If there are entries in ForwardRefBlockAddresses at this point, they are
70 // references after the function was defined. Resolve those now.
71 while (!ForwardRefBlockAddresses.empty()) {
72 // Okay, we are referencing an already-parsed function, resolve them now.
73 Function *TheFn = 0;
74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
75 if (Fn.Kind == ValID::t_GlobalName)
76 TheFn = M->getFunction(Fn.StrVal);
77 else if (Fn.UIntVal < NumberedVals.size())
78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
79
80 if (TheFn == 0)
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
82
83 // Resolve all these references.
84 if (ResolveForwardRefBlockAddresses(TheFn,
85 ForwardRefBlockAddresses.begin()->second,
86 0))
87 return true;
88
89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
90 }
91
Chris Lattner1afcace2011-07-09 17:41:24 +000092 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
93 if (NumberedTypes[i].second.isValid())
94 return Error(NumberedTypes[i].second,
95 "use of undefined type '%" + Twine(i) + "'");
96
97 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
98 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
99 if (I->second.second.isValid())
100 return Error(I->second.second,
101 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000102
Chris Lattnerdf986172009-01-02 07:01:27 +0000103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
106 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000107
Chris Lattnerdf986172009-01-02 07:01:27 +0000108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000111 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000112
Devang Patel1c7eea62009-07-08 19:23:54 +0000113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000116 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000117
Devang Patel1c7eea62009-07-08 19:23:54 +0000118
Chris Lattnerdf986172009-01-02 07:01:27 +0000119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000122
Chris Lattnerdf986172009-01-02 07:01:27 +0000123 return false;
124}
125
Chris Lattner09d9ef42009-10-28 03:39:23 +0000126bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
127 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
128 PerFunctionState *PFS) {
129 // Loop over all the references, resolving them.
130 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
131 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000132 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000133 if (Refs[i].first.Kind == ValID::t_LocalName)
134 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000135 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000136 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
137 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
138 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000139 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000140 } else {
141 Res = dyn_cast_or_null<BasicBlock>(
142 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
143 }
144
Chris Lattnercdfc9402009-11-01 01:27:45 +0000145 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000146 return Error(Refs[i].first.Loc,
147 "referenced value is not a basic block");
148
149 // Get the BlockAddress for this and update references to use it.
150 BlockAddress *BA = BlockAddress::get(TheFn, Res);
151 Refs[i].second->replaceAllUsesWith(BA);
152 Refs[i].second->eraseFromParent();
153 }
154 return false;
155}
156
157
Chris Lattnerdf986172009-01-02 07:01:27 +0000158//===----------------------------------------------------------------------===//
159// Top-Level Entities
160//===----------------------------------------------------------------------===//
161
162bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000163 while (1) {
164 switch (Lex.getKind()) {
165 default: return TokError("expected top-level entity");
166 case lltok::Eof: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000167 case lltok::kw_declare: if (ParseDeclare()) return true; break;
168 case lltok::kw_define: if (ParseDefine()) return true; break;
169 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
170 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
171 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000172 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000173 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000174 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000175 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000176 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000177 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000178
179 // The Global variable production with no name can have many different
180 // optional leading prefixes, the production is:
181 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000182 // OptionalAddrSpace OptionalUnNammedAddr
183 // ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000184 case lltok::kw_private: // OptionalLinkage
185 case lltok::kw_linker_private: // OptionalLinkage
186 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling32811be2012-08-17 18:33:14 +0000187 case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat.
Bill Wendling5e721d72010-07-01 21:55:59 +0000188 case lltok::kw_internal: // OptionalLinkage
189 case lltok::kw_weak: // OptionalLinkage
190 case lltok::kw_weak_odr: // OptionalLinkage
191 case lltok::kw_linkonce: // OptionalLinkage
192 case lltok::kw_linkonce_odr: // OptionalLinkage
Bill Wendling32811be2012-08-17 18:33:14 +0000193 case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000194 case lltok::kw_appending: // OptionalLinkage
195 case lltok::kw_dllexport: // OptionalLinkage
196 case lltok::kw_common: // OptionalLinkage
197 case lltok::kw_dllimport: // OptionalLinkage
198 case lltok::kw_extern_weak: // OptionalLinkage
199 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000200 unsigned Linkage, Visibility;
201 if (ParseOptionalLinkage(Linkage) ||
202 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000203 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000204 return true;
205 break;
206 }
207 case lltok::kw_default: // OptionalVisibility
208 case lltok::kw_hidden: // OptionalVisibility
209 case lltok::kw_protected: { // OptionalVisibility
210 unsigned Visibility;
211 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000212 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000213 return true;
214 break;
215 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000216
Chris Lattnerdf986172009-01-02 07:01:27 +0000217 case lltok::kw_thread_local: // OptionalThreadLocal
218 case lltok::kw_addrspace: // OptionalAddrSpace
219 case lltok::kw_constant: // GlobalType
220 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000221 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000222 break;
223 }
224 }
225}
226
227
228/// toplevelentity
229/// ::= 'module' 'asm' STRINGCONSTANT
230bool LLParser::ParseModuleAsm() {
231 assert(Lex.getKind() == lltok::kw_module);
232 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000233
234 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000235 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
236 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000237
Rafael Espindola38c4e532011-03-02 04:14:42 +0000238 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000239 return false;
240}
241
242/// toplevelentity
243/// ::= 'target' 'triple' '=' STRINGCONSTANT
244/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
245bool LLParser::ParseTargetDefinition() {
246 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000247 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000248 switch (Lex.Lex()) {
249 default: return TokError("unknown target property");
250 case lltok::kw_triple:
251 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000252 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
253 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000254 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000255 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000256 return false;
257 case lltok::kw_datalayout:
258 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000259 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
260 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000261 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000262 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000263 return false;
264 }
265}
266
267/// toplevelentity
268/// ::= 'deplibs' '=' '[' ']'
269/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
270bool LLParser::ParseDepLibs() {
271 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000272 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000273 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
274 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
275 return true;
276
277 if (EatIfPresent(lltok::rsquare))
278 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000279
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000280 std::string Str;
281 if (ParseStringConstant(Str)) return true;
282 M->addLibrary(Str);
283
284 while (EatIfPresent(lltok::comma)) {
285 if (ParseStringConstant(Str)) return true;
286 M->addLibrary(Str);
287 }
288
289 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000290}
291
Dan Gohman3845e502009-08-12 23:32:33 +0000292/// ParseUnnamedType:
Dan Gohman3845e502009-08-12 23:32:33 +0000293/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000294bool LLParser::ParseUnnamedType() {
Chris Lattneredcaca82011-06-18 23:51:31 +0000295 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +0000296 unsigned TypeID = Lex.getUIntVal();
Chris Lattnera53616d2011-06-19 00:03:46 +0000297 Lex.Lex(); // eat LocalVarID;
298
299 if (ParseToken(lltok::equal, "expected '=' after name") ||
300 ParseToken(lltok::kw_type, "expected 'type' after '='"))
301 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000302
Chris Lattner1afcace2011-07-09 17:41:24 +0000303 if (TypeID >= NumberedTypes.size())
304 NumberedTypes.resize(TypeID+1);
305
306 Type *Result = 0;
307 if (ParseStructDefinition(TypeLoc, "",
308 NumberedTypes[TypeID], Result)) return true;
309
310 if (!isa<StructType>(Result)) {
311 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
312 if (Entry.first)
313 return Error(TypeLoc, "non-struct types may not be recursive");
314 Entry.first = Result;
315 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000316 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000317
Chris Lattnerdf986172009-01-02 07:01:27 +0000318 return false;
319}
320
Chris Lattner1afcace2011-07-09 17:41:24 +0000321
Chris Lattnerdf986172009-01-02 07:01:27 +0000322/// toplevelentity
323/// ::= LocalVar '=' 'type' type
324bool LLParser::ParseNamedType() {
325 std::string Name = Lex.getStrVal();
326 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000327 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000328
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000329 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000330 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000331 return true;
Chris Lattner1afcace2011-07-09 17:41:24 +0000332
333 Type *Result = 0;
334 if (ParseStructDefinition(NameLoc, Name,
335 NamedTypes[Name], Result)) return true;
336
337 if (!isa<StructType>(Result)) {
338 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
339 if (Entry.first)
340 return Error(NameLoc, "non-struct types may not be recursive");
341 Entry.first = Result;
342 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000343 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000344
345 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000346}
347
348
349/// toplevelentity
350/// ::= 'declare' FunctionHeader
351bool LLParser::ParseDeclare() {
352 assert(Lex.getKind() == lltok::kw_declare);
353 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000354
Chris Lattnerdf986172009-01-02 07:01:27 +0000355 Function *F;
356 return ParseFunctionHeader(F, false);
357}
358
359/// toplevelentity
360/// ::= 'define' FunctionHeader '{' ...
361bool LLParser::ParseDefine() {
362 assert(Lex.getKind() == lltok::kw_define);
363 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000364
Chris Lattnerdf986172009-01-02 07:01:27 +0000365 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000366 return ParseFunctionHeader(F, true) ||
367 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000368}
369
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000370/// ParseGlobalType
371/// ::= 'constant'
372/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000373bool LLParser::ParseGlobalType(bool &IsConstant) {
374 if (Lex.getKind() == lltok::kw_constant)
375 IsConstant = true;
376 else if (Lex.getKind() == lltok::kw_global)
377 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000378 else {
379 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000380 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000381 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000382 Lex.Lex();
383 return false;
384}
385
Dan Gohman3845e502009-08-12 23:32:33 +0000386/// ParseUnnamedGlobal:
387/// OptionalVisibility ALIAS ...
388/// OptionalLinkage OptionalVisibility ... -> global variable
389/// GlobalID '=' OptionalVisibility ALIAS ...
390/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
391bool LLParser::ParseUnnamedGlobal() {
392 unsigned VarID = NumberedVals.size();
393 std::string Name;
394 LocTy NameLoc = Lex.getLoc();
395
396 // Handle the GlobalID form.
397 if (Lex.getKind() == lltok::GlobalID) {
398 if (Lex.getUIntVal() != VarID)
399 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000400 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000401 Lex.Lex(); // eat GlobalID;
402
403 if (ParseToken(lltok::equal, "expected '=' after name"))
404 return true;
405 }
406
407 bool HasLinkage;
408 unsigned Linkage, Visibility;
409 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
410 ParseOptionalVisibility(Visibility))
411 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000412
Dan Gohman3845e502009-08-12 23:32:33 +0000413 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
414 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
415 return ParseAlias(Name, NameLoc, Visibility);
416}
417
Chris Lattnerdf986172009-01-02 07:01:27 +0000418/// ParseNamedGlobal:
419/// GlobalVar '=' OptionalVisibility ALIAS ...
420/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
421bool LLParser::ParseNamedGlobal() {
422 assert(Lex.getKind() == lltok::GlobalVar);
423 LocTy NameLoc = Lex.getLoc();
424 std::string Name = Lex.getStrVal();
425 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000426
Chris Lattnerdf986172009-01-02 07:01:27 +0000427 bool HasLinkage;
428 unsigned Linkage, Visibility;
429 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
430 ParseOptionalLinkage(Linkage, HasLinkage) ||
431 ParseOptionalVisibility(Visibility))
432 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000433
Chris Lattnerdf986172009-01-02 07:01:27 +0000434 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
435 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
436 return ParseAlias(Name, NameLoc, Visibility);
437}
438
Devang Patel256be962009-07-20 19:00:08 +0000439// MDString:
440// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000441bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000442 std::string Str;
443 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000444 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000445 return false;
446}
447
448// MDNode:
449// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000450//
451/// This version of ParseMDNodeID returns the slot number and null in the case
452/// of a forward reference.
453bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
454 // !{ ..., !42, ... }
455 if (ParseUInt32(SlotNo)) return true;
456
457 // Check existing MDNode.
458 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
459 Result = NumberedMetadata[SlotNo];
460 else
461 Result = 0;
462 return false;
463}
464
Chris Lattner4a72efc2009-12-30 04:15:23 +0000465bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000466 // !{ ..., !42, ... }
467 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000468 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000469
Chris Lattner449c3102010-04-01 05:14:45 +0000470 // If not a forward reference, just return it now.
471 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000472
Chris Lattner449c3102010-04-01 05:14:45 +0000473 // Otherwise, create MDNode forward reference.
Jay Foadec9186b2011-04-21 19:59:31 +0000474 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Patel256be962009-07-20 19:00:08 +0000475 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000476
477 if (NumberedMetadata.size() <= MID)
478 NumberedMetadata.resize(MID+1);
479 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000480 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000481 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000482}
Devang Patel256be962009-07-20 19:00:08 +0000483
Chris Lattner84d03b12009-12-29 22:35:39 +0000484/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000485/// !foo = !{ !1, !2 }
486bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000487 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000488 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000489 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000490
Chris Lattner84d03b12009-12-29 22:35:39 +0000491 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000492 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000493 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000494 return true;
495
Dan Gohman17aa92c2010-07-21 23:38:33 +0000496 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000497 if (Lex.getKind() != lltok::rbrace)
498 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000499 if (ParseToken(lltok::exclaim, "Expected '!' here"))
500 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000501
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000502 MDNode *N = 0;
503 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000504 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000505 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000506
507 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
508 return true;
509
Devang Pateleff2ab62009-07-29 00:34:02 +0000510 return false;
511}
512
Devang Patel923078c2009-07-01 19:21:12 +0000513/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000514/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000515bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000516 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000517 Lex.Lex();
518 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000519
520 LocTy TyLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +0000521 Type *Ty = 0;
Devang Patel104cf9e2009-07-23 01:07:34 +0000522 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000523 if (ParseUInt32(MetadataID) ||
524 ParseToken(lltok::equal, "expected '=' here") ||
525 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000526 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000527 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000528 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000529 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000530 return true;
531
Jay Foadec9186b2011-04-21 19:59:31 +0000532 MDNode *Init = MDNode::get(Context, Elts);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000533
534 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000535 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000536 FI = ForwardRefMDNodes.find(MetadataID);
537 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000538 MDNode *Temp = FI->second.first;
539 Temp->replaceAllUsesWith(Init);
540 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000541 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000542
543 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
544 } else {
545 if (MetadataID >= NumberedMetadata.size())
546 NumberedMetadata.resize(MetadataID+1);
547
548 if (NumberedMetadata[MetadataID] != 0)
549 return TokError("Metadata id is already used");
550 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000551 }
552
Devang Patel923078c2009-07-01 19:21:12 +0000553 return false;
554}
555
Chris Lattnerdf986172009-01-02 07:01:27 +0000556/// ParseAlias:
557/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
558/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000559/// ::= TypeAndValue
560/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000561/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000562///
563/// Everything through visibility has already been parsed.
564///
565bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
566 unsigned Visibility) {
567 assert(Lex.getKind() == lltok::kw_alias);
568 Lex.Lex();
569 unsigned Linkage;
570 LocTy LinkageLoc = Lex.getLoc();
571 if (ParseOptionalLinkage(Linkage))
572 return true;
573
574 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000575 Linkage != GlobalValue::WeakAnyLinkage &&
576 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000577 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000578 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000579 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling32811be2012-08-17 18:33:14 +0000580 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000581 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000582
Chris Lattnerdf986172009-01-02 07:01:27 +0000583 Constant *Aliasee;
584 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000585 if (Lex.getKind() != lltok::kw_bitcast &&
586 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000587 if (ParseGlobalTypeAndValue(Aliasee)) return true;
588 } else {
589 // The bitcast dest type is not present, it is implied by the dest type.
590 ValID ID;
591 if (ParseValID(ID)) return true;
592 if (ID.Kind != ValID::t_Constant)
593 return Error(AliaseeLoc, "invalid aliasee");
594 Aliasee = ID.ConstantVal;
595 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000596
Duncan Sands1df98592010-02-16 11:11:14 +0000597 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000598 return Error(AliaseeLoc, "alias must have pointer type");
599
600 // Okay, create the alias but do not insert it into the module yet.
601 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
602 (GlobalValue::LinkageTypes)Linkage, Name,
603 Aliasee);
604 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000605
Chris Lattnerdf986172009-01-02 07:01:27 +0000606 // See if this value already exists in the symbol table. If so, it is either
607 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000608 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000609 // See if this was a redefinition. If so, there is no entry in
610 // ForwardRefVals.
611 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
612 I = ForwardRefVals.find(Name);
613 if (I == ForwardRefVals.end())
614 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
615
616 // Otherwise, this was a definition of forward ref. Verify that types
617 // agree.
618 if (Val->getType() != GA->getType())
619 return Error(NameLoc,
620 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000621
Chris Lattnerdf986172009-01-02 07:01:27 +0000622 // If they agree, just RAUW the old value with the alias and remove the
623 // forward ref info.
624 Val->replaceAllUsesWith(GA);
625 Val->eraseFromParent();
626 ForwardRefVals.erase(I);
627 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000628
Chris Lattnerdf986172009-01-02 07:01:27 +0000629 // Insert into the module, we know its name won't collide now.
630 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000631 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000632
Chris Lattnerdf986172009-01-02 07:01:27 +0000633 return false;
634}
635
636/// ParseGlobal
637/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000638/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000639/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000640/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000641///
642/// Everything through visibility has been parsed already.
643///
644bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
645 unsigned Linkage, bool HasLinkage,
646 unsigned Visibility) {
647 unsigned AddrSpace;
Hans Wennborgce718ff2012-06-23 11:37:03 +0000648 bool IsConstant, UnnamedAddr;
649 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000650 LocTy UnnamedAddrLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000651 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000652
Chris Lattner1afcace2011-07-09 17:41:24 +0000653 Type *Ty = 0;
Hans Wennborgce718ff2012-06-23 11:37:03 +0000654 if (ParseOptionalThreadLocal(TLM) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000655 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000656 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
657 &UnnamedAddrLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000658 ParseGlobalType(IsConstant) ||
659 ParseType(Ty, TyLoc))
660 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000661
Chris Lattnerdf986172009-01-02 07:01:27 +0000662 // If the linkage is specified and is external, then no initializer is
663 // present.
664 Constant *Init = 0;
665 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000666 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000667 Linkage != GlobalValue::ExternalLinkage)) {
668 if (ParseGlobalValue(Ty, Init))
669 return true;
670 }
671
Duncan Sands1df98592010-02-16 11:11:14 +0000672 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000673 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000674
Chris Lattnerdf986172009-01-02 07:01:27 +0000675 GlobalVariable *GV = 0;
676
677 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000678 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000679 if (GlobalValue *GVal = M->getNamedValue(Name)) {
680 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
681 return Error(NameLoc, "redefinition of global '@" + Name + "'");
682 GV = cast<GlobalVariable>(GVal);
683 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000684 } else {
685 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
686 I = ForwardRefValIDs.find(NumberedVals.size());
687 if (I != ForwardRefValIDs.end()) {
688 GV = cast<GlobalVariable>(I->second.first);
689 ForwardRefValIDs.erase(I);
690 }
691 }
692
693 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000694 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000695 Name, 0, GlobalVariable::NotThreadLocal,
696 AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000697 } else {
698 if (GV->getType()->getElementType() != Ty)
699 return Error(TyLoc,
700 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000701
Chris Lattnerdf986172009-01-02 07:01:27 +0000702 // Move the forward-reference to the correct spot in the module.
703 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
704 }
705
706 if (Name.empty())
707 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000708
Chris Lattnerdf986172009-01-02 07:01:27 +0000709 // Set the parsed properties on the global.
710 if (Init)
711 GV->setInitializer(Init);
712 GV->setConstant(IsConstant);
713 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
714 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Hans Wennborgce718ff2012-06-23 11:37:03 +0000715 GV->setThreadLocalMode(TLM);
Rafael Espindolabea46262011-01-08 16:42:36 +0000716 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000717
Chris Lattnerdf986172009-01-02 07:01:27 +0000718 // Parse attributes on the global.
719 while (Lex.getKind() == lltok::comma) {
720 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000721
Chris Lattnerdf986172009-01-02 07:01:27 +0000722 if (Lex.getKind() == lltok::kw_section) {
723 Lex.Lex();
724 GV->setSection(Lex.getStrVal());
725 if (ParseToken(lltok::StringConstant, "expected global section string"))
726 return true;
727 } else if (Lex.getKind() == lltok::kw_align) {
728 unsigned Alignment;
729 if (ParseOptionalAlignment(Alignment)) return true;
730 GV->setAlignment(Alignment);
731 } else {
732 TokError("unknown global variable property!");
733 }
734 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000735
Chris Lattnerdf986172009-01-02 07:01:27 +0000736 return false;
737}
738
739
740//===----------------------------------------------------------------------===//
741// GlobalValue Reference/Resolution Routines.
742//===----------------------------------------------------------------------===//
743
744/// GetGlobalVal - Get a value with the specified name or ID, creating a
745/// forward reference record if needed. This can return null if the value
746/// exists but does not have the right type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000747GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +0000748 LocTy Loc) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000749 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000750 if (PTy == 0) {
751 Error(Loc, "global variable reference must have pointer type");
752 return 0;
753 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000754
Chris Lattnerdf986172009-01-02 07:01:27 +0000755 // Look this name up in the normal function symbol table.
756 GlobalValue *Val =
757 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000758
Chris Lattnerdf986172009-01-02 07:01:27 +0000759 // If this is a forward reference for the value, see if we already created a
760 // forward ref record.
761 if (Val == 0) {
762 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
763 I = ForwardRefVals.find(Name);
764 if (I != ForwardRefVals.end())
765 Val = I->second.first;
766 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000767
Chris Lattnerdf986172009-01-02 07:01:27 +0000768 // If we have the value in the symbol table or fwd-ref table, return it.
769 if (Val) {
770 if (Val->getType() == Ty) return Val;
771 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000772 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000773 return 0;
774 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000775
Chris Lattnerdf986172009-01-02 07:01:27 +0000776 // Otherwise, create a new forward reference for this value and remember it.
777 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000778 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000779 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000780 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000781 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
782 GlobalValue::ExternalWeakLinkage, 0, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000783
Chris Lattnerdf986172009-01-02 07:01:27 +0000784 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
785 return FwdVal;
786}
787
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000788GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
789 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000790 if (PTy == 0) {
791 Error(Loc, "global variable reference must have pointer type");
792 return 0;
793 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000794
Chris Lattnerdf986172009-01-02 07:01:27 +0000795 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000796
Chris Lattnerdf986172009-01-02 07:01:27 +0000797 // If this is a forward reference for the value, see if we already created a
798 // forward ref record.
799 if (Val == 0) {
800 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
801 I = ForwardRefValIDs.find(ID);
802 if (I != ForwardRefValIDs.end())
803 Val = I->second.first;
804 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000805
Chris Lattnerdf986172009-01-02 07:01:27 +0000806 // If we have the value in the symbol table or fwd-ref table, return it.
807 if (Val) {
808 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000809 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000810 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000811 return 0;
812 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000813
Chris Lattnerdf986172009-01-02 07:01:27 +0000814 // Otherwise, create a new forward reference for this value and remember it.
815 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000816 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000817 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000818 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000819 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
820 GlobalValue::ExternalWeakLinkage, 0, "");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000821
Chris Lattnerdf986172009-01-02 07:01:27 +0000822 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
823 return FwdVal;
824}
825
826
827//===----------------------------------------------------------------------===//
828// Helper Routines.
829//===----------------------------------------------------------------------===//
830
831/// ParseToken - If the current token has the specified kind, eat it and return
832/// success. Otherwise, emit the specified error and return failure.
833bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
834 if (Lex.getKind() != T)
835 return TokError(ErrMsg);
836 Lex.Lex();
837 return false;
838}
839
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000840/// ParseStringConstant
841/// ::= StringConstant
842bool LLParser::ParseStringConstant(std::string &Result) {
843 if (Lex.getKind() != lltok::StringConstant)
844 return TokError("expected string constant");
845 Result = Lex.getStrVal();
846 Lex.Lex();
847 return false;
848}
849
850/// ParseUInt32
851/// ::= uint32
852bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000853 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
854 return TokError("expected integer");
855 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
856 if (Val64 != unsigned(Val64))
857 return TokError("expected 32-bit integer (too large)");
858 Val = Val64;
859 Lex.Lex();
860 return false;
861}
862
Hans Wennborgce718ff2012-06-23 11:37:03 +0000863/// ParseTLSModel
864/// := 'localdynamic'
865/// := 'initialexec'
866/// := 'localexec'
867bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
868 switch (Lex.getKind()) {
869 default:
870 return TokError("expected localdynamic, initialexec or localexec");
871 case lltok::kw_localdynamic:
872 TLM = GlobalVariable::LocalDynamicTLSModel;
873 break;
874 case lltok::kw_initialexec:
875 TLM = GlobalVariable::InitialExecTLSModel;
876 break;
877 case lltok::kw_localexec:
878 TLM = GlobalVariable::LocalExecTLSModel;
879 break;
880 }
881
882 Lex.Lex();
883 return false;
884}
885
886/// ParseOptionalThreadLocal
887/// := /*empty*/
888/// := 'thread_local'
889/// := 'thread_local' '(' tlsmodel ')'
890bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
891 TLM = GlobalVariable::NotThreadLocal;
892 if (!EatIfPresent(lltok::kw_thread_local))
893 return false;
894
895 TLM = GlobalVariable::GeneralDynamicTLSModel;
896 if (Lex.getKind() == lltok::lparen) {
897 Lex.Lex();
898 return ParseTLSModel(TLM) ||
899 ParseToken(lltok::rparen, "expected ')' after thread local model");
900 }
901 return false;
902}
Chris Lattnerdf986172009-01-02 07:01:27 +0000903
904/// ParseOptionalAddrSpace
905/// := /*empty*/
906/// := 'addrspace' '(' uint32 ')'
907bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
908 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000909 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000910 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000911 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000912 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000913 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000914}
Chris Lattnerdf986172009-01-02 07:01:27 +0000915
916/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
917/// indicates what kind of attribute list this is: 0: function arg, 1: result,
918/// 2: function attr.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000919bool LLParser::ParseOptionalAttrs(Attributes &Attrs, unsigned AttrKind) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000920 Attrs = Attribute::None;
921 LocTy AttrLoc = Lex.getLoc();
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000922 bool HaveError = false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000923
Chris Lattnerdf986172009-01-02 07:01:27 +0000924 while (1) {
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000925 lltok::Kind Token = Lex.getKind();
926 switch (Token) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000927 default: // End of attributes.
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000928 return HaveError;
Devang Patel578efa92009-06-05 21:57:13 +0000929 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
930 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
931 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
932 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
933 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
934 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
935 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
936 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000937
Devang Patel578efa92009-06-05 21:57:13 +0000938 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
939 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000940 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
Rafael Espindola25456ef2011-10-03 14:45:37 +0000941 case lltok::kw_returns_twice: Attrs |= Attribute::ReturnsTwice; break;
Devang Patel578efa92009-06-05 21:57:13 +0000942 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
943 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
944 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000945 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000946 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
947 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
948 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
949 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
950 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
951 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000952 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
John McCall3a3465b2011-06-15 20:36:13 +0000953 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000954 case lltok::kw_address_safety: Attrs |= Attribute::AddressSafety; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000955
Charles Davis1e063d12010-02-12 00:31:15 +0000956 case lltok::kw_alignstack: {
957 unsigned Alignment;
958 if (ParseOptionalStackAlignment(Alignment))
959 return true;
Bill Wendling30b483c2012-09-21 16:07:28 +0000960 Attrs |= Attributes::constructStackAlignmentFromInt(Alignment);
Charles Davis1e063d12010-02-12 00:31:15 +0000961 continue;
962 }
963
Chris Lattnerdf986172009-01-02 07:01:27 +0000964 case lltok::kw_align: {
965 unsigned Alignment;
966 if (ParseOptionalAlignment(Alignment))
967 return true;
Bill Wendling30b483c2012-09-21 16:07:28 +0000968 Attrs |= Attributes::constructAlignmentFromInt(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000969 continue;
970 }
Charles Davis1e063d12010-02-12 00:31:15 +0000971
Chris Lattnerdf986172009-01-02 07:01:27 +0000972 }
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000973
974 // Perform some error checking.
975 switch (Token) {
976 default:
977 if (AttrKind == 2)
978 HaveError |= Error(AttrLoc, "invalid use of attribute on a function");
979 break;
980 case lltok::kw_align:
981 // As a hack, we allow "align 2" on functions as a synonym for
982 // "alignstack 2".
983 break;
984
985 // Parameter Only:
986 case lltok::kw_sret:
987 case lltok::kw_nocapture:
988 case lltok::kw_byval:
989 case lltok::kw_nest:
990 if (AttrKind != 0)
991 HaveError |= Error(AttrLoc, "invalid use of parameter-only attribute");
992 break;
993
994 // Function Only:
995 case lltok::kw_noreturn:
996 case lltok::kw_nounwind:
997 case lltok::kw_readnone:
998 case lltok::kw_readonly:
999 case lltok::kw_noinline:
1000 case lltok::kw_alwaysinline:
1001 case lltok::kw_optsize:
1002 case lltok::kw_ssp:
1003 case lltok::kw_sspreq:
1004 case lltok::kw_noredzone:
1005 case lltok::kw_noimplicitfloat:
1006 case lltok::kw_naked:
1007 case lltok::kw_inlinehint:
1008 case lltok::kw_alignstack:
1009 case lltok::kw_uwtable:
1010 case lltok::kw_nonlazybind:
1011 case lltok::kw_returns_twice:
1012 case lltok::kw_address_safety:
1013 if (AttrKind != 2)
1014 HaveError |= Error(AttrLoc, "invalid use of function-only attribute");
1015 break;
1016 }
1017
Chris Lattnerdf986172009-01-02 07:01:27 +00001018 Lex.Lex();
1019 }
1020}
1021
1022/// ParseOptionalLinkage
1023/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001024/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001025/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001026/// ::= 'linker_private_weak'
Chris Lattnerdf986172009-01-02 07:01:27 +00001027/// ::= 'internal'
1028/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001029/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001030/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001031/// ::= 'linkonce_odr'
Bill Wendling32811be2012-08-17 18:33:14 +00001032/// ::= 'linkonce_odr_auto_hide'
Bill Wendling5e721d72010-07-01 21:55:59 +00001033/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001034/// ::= 'appending'
1035/// ::= 'dllexport'
1036/// ::= 'common'
1037/// ::= 'dllimport'
1038/// ::= 'extern_weak'
1039/// ::= 'external'
1040bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1041 HasLinkage = false;
1042 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001043 default: Res=GlobalValue::ExternalLinkage; return false;
1044 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1045 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001046 case lltok::kw_linker_private_weak:
1047 Res = GlobalValue::LinkerPrivateWeakLinkage;
1048 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001049 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1050 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1051 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1052 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1053 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Bill Wendling32811be2012-08-17 18:33:14 +00001054 case lltok::kw_linkonce_odr_auto_hide:
1055 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1056 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1057 break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001058 case lltok::kw_available_externally:
1059 Res = GlobalValue::AvailableExternallyLinkage;
1060 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001061 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1062 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1063 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1064 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1065 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1066 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001067 }
1068 Lex.Lex();
1069 HasLinkage = true;
1070 return false;
1071}
1072
1073/// ParseOptionalVisibility
1074/// ::= /*empty*/
1075/// ::= 'default'
1076/// ::= 'hidden'
1077/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001078///
Chris Lattnerdf986172009-01-02 07:01:27 +00001079bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1080 switch (Lex.getKind()) {
1081 default: Res = GlobalValue::DefaultVisibility; return false;
1082 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1083 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1084 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1085 }
1086 Lex.Lex();
1087 return false;
1088}
1089
1090/// ParseOptionalCallingConv
1091/// ::= /*empty*/
1092/// ::= 'ccc'
1093/// ::= 'fastcc'
1094/// ::= 'coldcc'
1095/// ::= 'x86_stdcallcc'
1096/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001097/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001098/// ::= 'arm_apcscc'
1099/// ::= 'arm_aapcscc'
1100/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001101/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001102/// ::= 'ptx_kernel'
1103/// ::= 'ptx_device'
Chris Lattnerdf986172009-01-02 07:01:27 +00001104/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001105///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001106bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001107 switch (Lex.getKind()) {
1108 default: CC = CallingConv::C; return false;
1109 case lltok::kw_ccc: CC = CallingConv::C; break;
1110 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1111 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1112 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1113 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001114 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001115 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1116 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1117 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001118 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001119 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1120 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001121 case lltok::kw_cc: {
1122 unsigned ArbitraryCC;
1123 Lex.Lex();
David Blaikie4d6ccb52012-01-20 21:51:11 +00001124 if (ParseUInt32(ArbitraryCC))
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001125 return true;
David Blaikie4d6ccb52012-01-20 21:51:11 +00001126 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1127 return false;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001128 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001129 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001130
Chris Lattnerdf986172009-01-02 07:01:27 +00001131 Lex.Lex();
1132 return false;
1133}
1134
Chris Lattnerb8c46862009-12-30 05:31:19 +00001135/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001136/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001137bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1138 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001139 do {
1140 if (Lex.getKind() != lltok::MetadataVar)
1141 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001142
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001143 std::string Name = Lex.getStrVal();
Benjamin Kramer85dadec2011-12-06 11:50:26 +00001144 unsigned MDK = M->getMDKindID(Name);
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001145 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001146
Chris Lattner442ffa12009-12-29 21:53:55 +00001147 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001148 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001149
1150 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001151 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001152
Dan Gohman68261142010-08-24 14:35:45 +00001153 // This code is similar to that of ParseMetadataValue, however it needs to
1154 // have special-case code for a forward reference; see the comments on
1155 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1156 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001157 if (Lex.getKind() == lltok::lbrace) {
1158 ValID ID;
1159 if (ParseMetadataListValue(ID, PFS))
1160 return true;
1161 assert(ID.Kind == ValID::t_MDNode);
1162 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001163 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001164 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001165 if (ParseMDNodeID(Node, NodeID))
1166 return true;
1167 if (Node) {
1168 // If we got the node, add it to the instruction.
1169 Inst->setMetadata(MDK, Node);
1170 } else {
1171 MDRef R = { Loc, MDK, NodeID };
1172 // Otherwise, remember that this should be resolved later.
1173 ForwardRefInstMetadata[Inst].push_back(R);
1174 }
Chris Lattner449c3102010-04-01 05:14:45 +00001175 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001176
1177 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001178 } while (EatIfPresent(lltok::comma));
1179 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001180}
1181
Chris Lattnerdf986172009-01-02 07:01:27 +00001182/// ParseOptionalAlignment
1183/// ::= /* empty */
1184/// ::= 'align' 4
1185bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1186 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001187 if (!EatIfPresent(lltok::kw_align))
1188 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001189 LocTy AlignLoc = Lex.getLoc();
1190 if (ParseUInt32(Alignment)) return true;
1191 if (!isPowerOf2_32(Alignment))
1192 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001193 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001194 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001195 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001196}
1197
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001198/// ParseOptionalCommaAlign
1199/// ::=
1200/// ::= ',' align 4
1201///
1202/// This returns with AteExtraComma set to true if it ate an excess comma at the
1203/// end.
1204bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1205 bool &AteExtraComma) {
1206 AteExtraComma = false;
1207 while (EatIfPresent(lltok::comma)) {
1208 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001209 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001210 AteExtraComma = true;
1211 return false;
1212 }
1213
Chris Lattner093eed12010-04-23 00:50:50 +00001214 if (Lex.getKind() != lltok::kw_align)
1215 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001216
Chris Lattner093eed12010-04-23 00:50:50 +00001217 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001218 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001219
Devang Patelf633a062009-09-17 23:04:48 +00001220 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001221}
1222
Eli Friedman47f35132011-07-25 23:16:38 +00001223/// ParseScopeAndOrdering
1224/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1225/// else: ::=
1226///
1227/// This sets Scope and Ordering to the parsed values.
1228bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1229 AtomicOrdering &Ordering) {
1230 if (!isAtomic)
1231 return false;
1232
1233 Scope = CrossThread;
1234 if (EatIfPresent(lltok::kw_singlethread))
1235 Scope = SingleThread;
1236 switch (Lex.getKind()) {
1237 default: return TokError("Expected ordering on atomic instruction");
1238 case lltok::kw_unordered: Ordering = Unordered; break;
1239 case lltok::kw_monotonic: Ordering = Monotonic; break;
1240 case lltok::kw_acquire: Ordering = Acquire; break;
1241 case lltok::kw_release: Ordering = Release; break;
1242 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1243 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1244 }
1245 Lex.Lex();
1246 return false;
1247}
1248
Charles Davis1e063d12010-02-12 00:31:15 +00001249/// ParseOptionalStackAlignment
1250/// ::= /* empty */
1251/// ::= 'alignstack' '(' 4 ')'
1252bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1253 Alignment = 0;
1254 if (!EatIfPresent(lltok::kw_alignstack))
1255 return false;
1256 LocTy ParenLoc = Lex.getLoc();
1257 if (!EatIfPresent(lltok::lparen))
1258 return Error(ParenLoc, "expected '('");
1259 LocTy AlignLoc = Lex.getLoc();
1260 if (ParseUInt32(Alignment)) return true;
1261 ParenLoc = Lex.getLoc();
1262 if (!EatIfPresent(lltok::rparen))
1263 return Error(ParenLoc, "expected ')'");
1264 if (!isPowerOf2_32(Alignment))
1265 return Error(AlignLoc, "stack alignment is not a power of two");
1266 return false;
1267}
Devang Patelf633a062009-09-17 23:04:48 +00001268
Chris Lattner628c13a2009-12-30 05:14:00 +00001269/// ParseIndexList - This parses the index list for an insert/extractvalue
1270/// instruction. This sets AteExtraComma in the case where we eat an extra
1271/// comma at the end of the line and find that it is followed by metadata.
1272/// Clients that don't allow metadata can call the version of this function that
1273/// only takes one argument.
1274///
Chris Lattnerdf986172009-01-02 07:01:27 +00001275/// ParseIndexList
1276/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001277///
1278bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1279 bool &AteExtraComma) {
1280 AteExtraComma = false;
1281
Chris Lattnerdf986172009-01-02 07:01:27 +00001282 if (Lex.getKind() != lltok::comma)
1283 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001284
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001285 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001286 if (Lex.getKind() == lltok::MetadataVar) {
1287 AteExtraComma = true;
1288 return false;
1289 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001290 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001291 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001292 Indices.push_back(Idx);
1293 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001294
Chris Lattnerdf986172009-01-02 07:01:27 +00001295 return false;
1296}
1297
1298//===----------------------------------------------------------------------===//
1299// Type Parsing.
1300//===----------------------------------------------------------------------===//
1301
Chris Lattner1afcace2011-07-09 17:41:24 +00001302/// ParseType - Parse a type.
1303bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1304 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001305 switch (Lex.getKind()) {
1306 default:
1307 return TokError("expected type");
1308 case lltok::Type:
Chris Lattner1afcace2011-07-09 17:41:24 +00001309 // Type ::= 'float' | 'void' (etc)
Chris Lattnerdf986172009-01-02 07:01:27 +00001310 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001311 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001312 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001313 case lltok::lbrace:
Chris Lattner1afcace2011-07-09 17:41:24 +00001314 // Type ::= StructType
1315 if (ParseAnonStructType(Result, false))
Chris Lattnerdf986172009-01-02 07:01:27 +00001316 return true;
1317 break;
1318 case lltok::lsquare:
Chris Lattner1afcace2011-07-09 17:41:24 +00001319 // Type ::= '[' ... ']'
Chris Lattnerdf986172009-01-02 07:01:27 +00001320 Lex.Lex(); // eat the lsquare.
1321 if (ParseArrayVectorType(Result, false))
1322 return true;
1323 break;
1324 case lltok::less: // Either vector or packed struct.
Chris Lattner1afcace2011-07-09 17:41:24 +00001325 // Type ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001326 Lex.Lex();
1327 if (Lex.getKind() == lltok::lbrace) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001328 if (ParseAnonStructType(Result, true) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001329 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001330 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001331 } else if (ParseArrayVectorType(Result, true))
1332 return true;
1333 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001334 case lltok::LocalVar: {
1335 // Type ::= %foo
1336 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1337
1338 // If the type hasn't been defined yet, create a forward definition and
1339 // remember where that forward def'n was seen (in case it never is defined).
1340 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001341 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattner1afcace2011-07-09 17:41:24 +00001342 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001343 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001344 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001345 Lex.Lex();
1346 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001347 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001348
Chris Lattner1afcace2011-07-09 17:41:24 +00001349 case lltok::LocalVarID: {
1350 // Type ::= %4
1351 if (Lex.getUIntVal() >= NumberedTypes.size())
1352 NumberedTypes.resize(Lex.getUIntVal()+1);
1353 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1354
1355 // If the type hasn't been defined yet, create a forward definition and
1356 // remember where that forward def'n was seen (in case it never is defined).
1357 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001358 Entry.first = StructType::create(Context);
Chris Lattner1afcace2011-07-09 17:41:24 +00001359 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001360 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001361 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001362 Lex.Lex();
1363 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001364 }
1365 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001366
1367 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001368 while (1) {
1369 switch (Lex.getKind()) {
1370 // End of type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001371 default:
1372 if (!AllowVoid && Result->isVoidTy())
1373 return Error(TypeLoc, "void type only allowed for function results");
1374 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001375
Chris Lattner1afcace2011-07-09 17:41:24 +00001376 // Type ::= Type '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001377 case lltok::star:
Chris Lattner1afcace2011-07-09 17:41:24 +00001378 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001379 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001380 if (Result->isVoidTy())
1381 return TokError("pointers to void are invalid - use i8* instead");
1382 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001383 return TokError("pointer to this type is invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001384 Result = PointerType::getUnqual(Result);
Chris Lattnerdf986172009-01-02 07:01:27 +00001385 Lex.Lex();
1386 break;
1387
Chris Lattner1afcace2011-07-09 17:41:24 +00001388 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001389 case lltok::kw_addrspace: {
Chris Lattner1afcace2011-07-09 17:41:24 +00001390 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001391 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001392 if (Result->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001393 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattner1afcace2011-07-09 17:41:24 +00001394 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001395 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001396 unsigned AddrSpace;
1397 if (ParseOptionalAddrSpace(AddrSpace) ||
1398 ParseToken(lltok::star, "expected '*' in address space"))
1399 return true;
1400
Chris Lattner1afcace2011-07-09 17:41:24 +00001401 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001402 break;
1403 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001404
Chris Lattnerdf986172009-01-02 07:01:27 +00001405 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1406 case lltok::lparen:
1407 if (ParseFunctionType(Result))
1408 return true;
1409 break;
1410 }
1411 }
1412}
1413
1414/// ParseParameterList
1415/// ::= '(' ')'
1416/// ::= '(' Arg (',' Arg)* ')'
1417/// Arg
1418/// ::= Type OptionalAttributes Value OptionalAttributes
1419bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1420 PerFunctionState &PFS) {
1421 if (ParseToken(lltok::lparen, "expected '(' in call"))
1422 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001423
Chris Lattnerdf986172009-01-02 07:01:27 +00001424 while (Lex.getKind() != lltok::rparen) {
1425 // If this isn't the first argument, we need a comma.
1426 if (!ArgList.empty() &&
1427 ParseToken(lltok::comma, "expected ',' in argument list"))
1428 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001429
Chris Lattnerdf986172009-01-02 07:01:27 +00001430 // Parse the argument.
1431 LocTy ArgLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +00001432 Type *ArgTy = 0;
Kostya Serebryany164b86b2012-01-20 17:56:17 +00001433 Attributes ArgAttrs1;
1434 Attributes ArgAttrs2;
Chris Lattnerdf986172009-01-02 07:01:27 +00001435 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001436 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001437 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001438
Chris Lattner287881d2009-12-30 02:11:14 +00001439 // Otherwise, handle normal operands.
Chris Lattnerf3a789d2011-06-17 03:16:47 +00001440 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001441 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001442 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1443 }
1444
1445 Lex.Lex(); // Lex the ')'.
1446 return false;
1447}
1448
1449
1450
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001451/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattner1afcace2011-07-09 17:41:24 +00001452/// prototype.
Chris Lattnerdf986172009-01-02 07:01:27 +00001453/// ::= '(' ArgTypeListI ')'
1454/// ArgTypeListI
1455/// ::= /*empty*/
1456/// ::= '...'
1457/// ::= ArgTypeList ',' '...'
1458/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001459///
Chris Lattner1afcace2011-07-09 17:41:24 +00001460bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1461 bool &isVarArg){
Chris Lattnerdf986172009-01-02 07:01:27 +00001462 isVarArg = false;
1463 assert(Lex.getKind() == lltok::lparen);
1464 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001465
Chris Lattnerdf986172009-01-02 07:01:27 +00001466 if (Lex.getKind() == lltok::rparen) {
1467 // empty
1468 } else if (Lex.getKind() == lltok::dotdotdot) {
1469 isVarArg = true;
1470 Lex.Lex();
1471 } else {
1472 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001473 Type *ArgTy = 0;
Kostya Serebryany164b86b2012-01-20 17:56:17 +00001474 Attributes Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001475 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001476
Chris Lattner1afcace2011-07-09 17:41:24 +00001477 if (ParseType(ArgTy) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001478 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001479
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001480 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001481 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001482
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001483 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001484 Name = Lex.getStrVal();
1485 Lex.Lex();
1486 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001487
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001488 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001489 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001490
Chris Lattnerdf986172009-01-02 07:01:27 +00001491 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001492
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001493 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001494 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001495 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001496 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001497 break;
1498 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001499
Chris Lattnerdf986172009-01-02 07:01:27 +00001500 // Otherwise must be an argument type.
1501 TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001502 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001503
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001504 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001505 return Error(TypeLoc, "argument can not have void type");
1506
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001507 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001508 Name = Lex.getStrVal();
1509 Lex.Lex();
1510 } else {
1511 Name = "";
1512 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001513
Chris Lattner1afcace2011-07-09 17:41:24 +00001514 if (!ArgTy->isFirstClassType())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001515 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001516
Chris Lattnerdf986172009-01-02 07:01:27 +00001517 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1518 }
1519 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001520
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001521 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001522}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001523
Chris Lattnerdf986172009-01-02 07:01:27 +00001524/// ParseFunctionType
1525/// ::= Type ArgumentList OptionalAttrs
Chris Lattner1afcace2011-07-09 17:41:24 +00001526bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001527 assert(Lex.getKind() == lltok::lparen);
1528
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001529 if (!FunctionType::isValidReturnType(Result))
1530 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001531
Chris Lattner1afcace2011-07-09 17:41:24 +00001532 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00001533 bool isVarArg;
Chris Lattner1afcace2011-07-09 17:41:24 +00001534 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerdf986172009-01-02 07:01:27 +00001535 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001536
Chris Lattnerdf986172009-01-02 07:01:27 +00001537 // Reject names on the arguments lists.
1538 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1539 if (!ArgList[i].Name.empty())
1540 return Error(ArgList[i].Loc, "argument name invalid in function type");
Kostya Serebryany164b86b2012-01-20 17:56:17 +00001541 if (ArgList[i].Attrs)
Chris Lattnera16546a2011-06-17 17:37:13 +00001542 return Error(ArgList[i].Loc,
1543 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001544 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001545
Jay Foad5fdd6c82011-07-12 14:06:48 +00001546 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerdf986172009-01-02 07:01:27 +00001547 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattner1afcace2011-07-09 17:41:24 +00001548 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001549
Chris Lattner1afcace2011-07-09 17:41:24 +00001550 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerdf986172009-01-02 07:01:27 +00001551 return false;
1552}
1553
Chris Lattner1afcace2011-07-09 17:41:24 +00001554/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1555/// other structs.
1556bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1557 SmallVector<Type*, 8> Elts;
1558 if (ParseStructBody(Elts)) return true;
1559
1560 Result = StructType::get(Context, Elts, Packed);
1561 return false;
1562}
1563
1564/// ParseStructDefinition - Parse a struct in a 'type' definition.
1565bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1566 std::pair<Type*, LocTy> &Entry,
1567 Type *&ResultTy) {
1568 // If the type was already defined, diagnose the redefinition.
1569 if (Entry.first && !Entry.second.isValid())
1570 return Error(TypeLoc, "redefinition of type");
1571
1572 // If we have opaque, just return without filling in the definition for the
1573 // struct. This counts as a definition as far as the .ll file goes.
1574 if (EatIfPresent(lltok::kw_opaque)) {
1575 // This type is being defined, so clear the location to indicate this.
1576 Entry.second = SMLoc();
1577
1578 // If this type number has never been uttered, create it.
1579 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001580 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001581 ResultTy = Entry.first;
1582 return false;
1583 }
1584
1585 // If the type starts with '<', then it is either a packed struct or a vector.
1586 bool isPacked = EatIfPresent(lltok::less);
1587
1588 // If we don't have a struct, then we have a random type alias, which we
1589 // accept for compatibility with old files. These types are not allowed to be
1590 // forward referenced and not allowed to be recursive.
1591 if (Lex.getKind() != lltok::lbrace) {
1592 if (Entry.first)
1593 return Error(TypeLoc, "forward references to non-struct type");
1594
1595 ResultTy = 0;
1596 if (isPacked)
1597 return ParseArrayVectorType(ResultTy, true);
1598 return ParseType(ResultTy);
1599 }
1600
1601 // This type is being defined, so clear the location to indicate this.
1602 Entry.second = SMLoc();
1603
1604 // If this type number has never been uttered, create it.
1605 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001606 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001607
1608 StructType *STy = cast<StructType>(Entry.first);
1609
1610 SmallVector<Type*, 8> Body;
1611 if (ParseStructBody(Body) ||
1612 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1613 return true;
1614
1615 STy->setBody(Body, isPacked);
1616 ResultTy = STy;
1617 return false;
1618}
1619
1620
Chris Lattnerdf986172009-01-02 07:01:27 +00001621/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattner1afcace2011-07-09 17:41:24 +00001622/// StructType
Chris Lattnerdf986172009-01-02 07:01:27 +00001623/// ::= '{' '}'
Chris Lattner1afcace2011-07-09 17:41:24 +00001624/// ::= '{' Type (',' Type)* '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00001625/// ::= '<' '{' '}' '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001626/// ::= '<' '{' Type (',' Type)* '}' '>'
1627bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001628 assert(Lex.getKind() == lltok::lbrace);
1629 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001630
Chris Lattner1afcace2011-07-09 17:41:24 +00001631 // Handle the empty struct.
1632 if (EatIfPresent(lltok::rbrace))
Chris Lattnerdf986172009-01-02 07:01:27 +00001633 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001634
Chris Lattnera9a9e072009-03-09 04:49:14 +00001635 LocTy EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001636 Type *Ty = 0;
1637 if (ParseType(Ty)) return true;
1638 Body.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001639
Chris Lattner1afcace2011-07-09 17:41:24 +00001640 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001641 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001642
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001643 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001644 EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001645 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001646
Chris Lattner1afcace2011-07-09 17:41:24 +00001647 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001648 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001649
Chris Lattner1afcace2011-07-09 17:41:24 +00001650 Body.push_back(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00001651 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001652
Chris Lattner1afcace2011-07-09 17:41:24 +00001653 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerdf986172009-01-02 07:01:27 +00001654}
1655
1656/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1657/// token has already been consumed.
Chris Lattner1afcace2011-07-09 17:41:24 +00001658/// Type
Chris Lattnerdf986172009-01-02 07:01:27 +00001659/// ::= '[' APSINTVAL 'x' Types ']'
1660/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001661bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001662 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1663 Lex.getAPSIntVal().getBitWidth() > 64)
1664 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001665
Chris Lattnerdf986172009-01-02 07:01:27 +00001666 LocTy SizeLoc = Lex.getLoc();
1667 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001668 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001669
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001670 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1671 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001672
1673 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001674 Type *EltTy = 0;
1675 if (ParseType(EltTy)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001676
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001677 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1678 "expected end of sequential type"))
1679 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001680
Chris Lattnerdf986172009-01-02 07:01:27 +00001681 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001682 if (Size == 0)
1683 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001684 if ((unsigned)Size != Size)
1685 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001686 if (!VectorType::isValidElementType(EltTy))
Nadav Rotem16087692011-12-05 06:29:09 +00001687 return Error(TypeLoc,
1688 "vector element type must be fp, integer or a pointer to these types");
Owen Andersondebcb012009-07-29 22:17:13 +00001689 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001690 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001691 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001692 return Error(TypeLoc, "invalid array element type");
Chris Lattner1afcace2011-07-09 17:41:24 +00001693 Result = ArrayType::get(EltTy, Size);
Chris Lattnerdf986172009-01-02 07:01:27 +00001694 }
1695 return false;
1696}
1697
1698//===----------------------------------------------------------------------===//
1699// Function Semantic Analysis.
1700//===----------------------------------------------------------------------===//
1701
Chris Lattner09d9ef42009-10-28 03:39:23 +00001702LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1703 int functionNumber)
1704 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001705
1706 // Insert unnamed arguments into the NumberedVals list.
1707 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1708 AI != E; ++AI)
1709 if (!AI->hasName())
1710 NumberedVals.push_back(AI);
1711}
1712
1713LLParser::PerFunctionState::~PerFunctionState() {
1714 // If there were any forward referenced non-basicblock values, delete them.
1715 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1716 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1717 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001718 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001719 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001720 delete I->second.first;
1721 I->second.first = 0;
1722 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001723
Chris Lattnerdf986172009-01-02 07:01:27 +00001724 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1725 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1726 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001727 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001728 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001729 delete I->second.first;
1730 I->second.first = 0;
1731 }
1732}
1733
Chris Lattner09d9ef42009-10-28 03:39:23 +00001734bool LLParser::PerFunctionState::FinishFunction() {
1735 // Check to see if someone took the address of labels in this block.
1736 if (!P.ForwardRefBlockAddresses.empty()) {
1737 ValID FunctionID;
1738 if (!F.getName().empty()) {
1739 FunctionID.Kind = ValID::t_GlobalName;
1740 FunctionID.StrVal = F.getName();
1741 } else {
1742 FunctionID.Kind = ValID::t_GlobalID;
1743 FunctionID.UIntVal = FunctionNumber;
1744 }
1745
1746 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1747 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1748 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1749 // Resolve all these references.
1750 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1751 return true;
1752
1753 P.ForwardRefBlockAddresses.erase(FRBAI);
1754 }
1755 }
1756
Chris Lattnerdf986172009-01-02 07:01:27 +00001757 if (!ForwardRefVals.empty())
1758 return P.Error(ForwardRefVals.begin()->second.second,
1759 "use of undefined value '%" + ForwardRefVals.begin()->first +
1760 "'");
1761 if (!ForwardRefValIDs.empty())
1762 return P.Error(ForwardRefValIDs.begin()->second.second,
1763 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001764 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001765 return false;
1766}
1767
1768
1769/// GetVal - Get a value with the specified name or ID, creating a
1770/// forward reference record if needed. This can return null if the value
1771/// exists but does not have the right type.
1772Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001773 Type *Ty, LocTy Loc) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001774 // Look this name up in the normal function symbol table.
1775 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001776
Chris Lattnerdf986172009-01-02 07:01:27 +00001777 // If this is a forward reference for the value, see if we already created a
1778 // forward ref record.
1779 if (Val == 0) {
1780 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1781 I = ForwardRefVals.find(Name);
1782 if (I != ForwardRefVals.end())
1783 Val = I->second.first;
1784 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001785
Chris Lattnerdf986172009-01-02 07:01:27 +00001786 // If we have the value in the symbol table or fwd-ref table, return it.
1787 if (Val) {
1788 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001789 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001790 P.Error(Loc, "'%" + Name + "' is not a basic block");
1791 else
1792 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001793 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001794 return 0;
1795 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001796
Chris Lattnerdf986172009-01-02 07:01:27 +00001797 // Don't make placeholders with invalid type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001798 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001799 P.Error(Loc, "invalid use of a non-first-class type");
1800 return 0;
1801 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001802
Chris Lattnerdf986172009-01-02 07:01:27 +00001803 // Otherwise, create a new forward reference for this value and remember it.
1804 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001805 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001806 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001807 else
1808 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001809
Chris Lattnerdf986172009-01-02 07:01:27 +00001810 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1811 return FwdVal;
1812}
1813
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001814Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +00001815 LocTy Loc) {
1816 // Look this name up in the normal function symbol table.
1817 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001818
Chris Lattnerdf986172009-01-02 07:01:27 +00001819 // If this is a forward reference for the value, see if we already created a
1820 // forward ref record.
1821 if (Val == 0) {
1822 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1823 I = ForwardRefValIDs.find(ID);
1824 if (I != ForwardRefValIDs.end())
1825 Val = I->second.first;
1826 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001827
Chris Lattnerdf986172009-01-02 07:01:27 +00001828 // If we have the value in the symbol table or fwd-ref table, return it.
1829 if (Val) {
1830 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001831 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001832 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001833 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001834 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001835 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001836 return 0;
1837 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001838
Chris Lattner1afcace2011-07-09 17:41:24 +00001839 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001840 P.Error(Loc, "invalid use of a non-first-class type");
1841 return 0;
1842 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001843
Chris Lattnerdf986172009-01-02 07:01:27 +00001844 // Otherwise, create a new forward reference for this value and remember it.
1845 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001846 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001847 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001848 else
1849 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001850
Chris Lattnerdf986172009-01-02 07:01:27 +00001851 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1852 return FwdVal;
1853}
1854
1855/// SetInstName - After an instruction is parsed and inserted into its
1856/// basic block, this installs its name.
1857bool LLParser::PerFunctionState::SetInstName(int NameID,
1858 const std::string &NameStr,
1859 LocTy NameLoc, Instruction *Inst) {
1860 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001861 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001862 if (NameID != -1 || !NameStr.empty())
1863 return P.Error(NameLoc, "instructions returning void cannot have a name");
1864 return false;
1865 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001866
Chris Lattnerdf986172009-01-02 07:01:27 +00001867 // If this was a numbered instruction, verify that the instruction is the
1868 // expected value and resolve any forward references.
1869 if (NameStr.empty()) {
1870 // If neither a name nor an ID was specified, just use the next ID.
1871 if (NameID == -1)
1872 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001873
Chris Lattnerdf986172009-01-02 07:01:27 +00001874 if (unsigned(NameID) != NumberedVals.size())
1875 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001876 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001877
Chris Lattnerdf986172009-01-02 07:01:27 +00001878 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1879 ForwardRefValIDs.find(NameID);
1880 if (FI != ForwardRefValIDs.end()) {
1881 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001882 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001883 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001884 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001885 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001886 ForwardRefValIDs.erase(FI);
1887 }
1888
1889 NumberedVals.push_back(Inst);
1890 return false;
1891 }
1892
1893 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1894 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1895 FI = ForwardRefVals.find(NameStr);
1896 if (FI != ForwardRefVals.end()) {
1897 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001898 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001899 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001900 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001901 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001902 ForwardRefVals.erase(FI);
1903 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001904
Chris Lattnerdf986172009-01-02 07:01:27 +00001905 // Set the name on the instruction.
1906 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001907
Benjamin Krameraf812352010-10-16 11:28:23 +00001908 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001909 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001910 NameStr + "'");
1911 return false;
1912}
1913
1914/// GetBB - Get a basic block with the specified name or ID, creating a
1915/// forward reference record if needed.
1916BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1917 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001918 return cast_or_null<BasicBlock>(GetVal(Name,
1919 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001920}
1921
1922BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001923 return cast_or_null<BasicBlock>(GetVal(ID,
1924 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001925}
1926
1927/// DefineBB - Define the specified basic block, which is either named or
1928/// unnamed. If there is an error, this returns null otherwise it returns
1929/// the block being defined.
1930BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1931 LocTy Loc) {
1932 BasicBlock *BB;
1933 if (Name.empty())
1934 BB = GetBB(NumberedVals.size(), Loc);
1935 else
1936 BB = GetBB(Name, Loc);
1937 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001938
Chris Lattnerdf986172009-01-02 07:01:27 +00001939 // Move the block to the end of the function. Forward ref'd blocks are
1940 // inserted wherever they happen to be referenced.
1941 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001942
Chris Lattnerdf986172009-01-02 07:01:27 +00001943 // Remove the block from forward ref sets.
1944 if (Name.empty()) {
1945 ForwardRefValIDs.erase(NumberedVals.size());
1946 NumberedVals.push_back(BB);
1947 } else {
1948 // BB forward references are already in the function symbol table.
1949 ForwardRefVals.erase(Name);
1950 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001951
Chris Lattnerdf986172009-01-02 07:01:27 +00001952 return BB;
1953}
1954
1955//===----------------------------------------------------------------------===//
1956// Constants.
1957//===----------------------------------------------------------------------===//
1958
1959/// ParseValID - Parse an abstract value that doesn't necessarily have a
1960/// type implied. For example, if we parse "4" we don't know what integer type
1961/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001962/// sanity. PFS is used to convert function-local operands of metadata (since
1963/// metadata operands are not just parsed here but also converted to values).
1964/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001965bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001966 ID.Loc = Lex.getLoc();
1967 switch (Lex.getKind()) {
1968 default: return TokError("expected value token");
1969 case lltok::GlobalID: // @42
1970 ID.UIntVal = Lex.getUIntVal();
1971 ID.Kind = ValID::t_GlobalID;
1972 break;
1973 case lltok::GlobalVar: // @foo
1974 ID.StrVal = Lex.getStrVal();
1975 ID.Kind = ValID::t_GlobalName;
1976 break;
1977 case lltok::LocalVarID: // %42
1978 ID.UIntVal = Lex.getUIntVal();
1979 ID.Kind = ValID::t_LocalID;
1980 break;
1981 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00001982 ID.StrVal = Lex.getStrVal();
1983 ID.Kind = ValID::t_LocalName;
1984 break;
Dan Gohman83448032010-07-14 18:26:50 +00001985 case lltok::exclaim: // !42, !{...}, or !"foo"
1986 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00001987 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001988 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001989 ID.Kind = ValID::t_APSInt;
1990 break;
1991 case lltok::APFloat:
1992 ID.APFloatVal = Lex.getAPFloatVal();
1993 ID.Kind = ValID::t_APFloat;
1994 break;
1995 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001996 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001997 ID.Kind = ValID::t_Constant;
1998 break;
1999 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002000 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002001 ID.Kind = ValID::t_Constant;
2002 break;
2003 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2004 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2005 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002006
Chris Lattnerdf986172009-01-02 07:01:27 +00002007 case lltok::lbrace: {
2008 // ValID ::= '{' ConstVector '}'
2009 Lex.Lex();
2010 SmallVector<Constant*, 16> Elts;
2011 if (ParseGlobalValueVector(Elts) ||
2012 ParseToken(lltok::rbrace, "expected end of struct constant"))
2013 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002014
Chris Lattner1afcace2011-07-09 17:41:24 +00002015 ID.ConstantStructElts = new Constant*[Elts.size()];
2016 ID.UIntVal = Elts.size();
2017 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2018 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002019 return false;
2020 }
2021 case lltok::less: {
2022 // ValID ::= '<' ConstVector '>' --> Vector.
2023 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2024 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002025 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002026
Chris Lattnerdf986172009-01-02 07:01:27 +00002027 SmallVector<Constant*, 16> Elts;
2028 LocTy FirstEltLoc = Lex.getLoc();
2029 if (ParseGlobalValueVector(Elts) ||
2030 (isPackedStruct &&
2031 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2032 ParseToken(lltok::greater, "expected end of constant"))
2033 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002034
Chris Lattnerdf986172009-01-02 07:01:27 +00002035 if (isPackedStruct) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002036 ID.ConstantStructElts = new Constant*[Elts.size()];
2037 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2038 ID.UIntVal = Elts.size();
2039 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002040 return false;
2041 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002042
Chris Lattnerdf986172009-01-02 07:01:27 +00002043 if (Elts.empty())
2044 return Error(ID.Loc, "constant vector must not be empty");
2045
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002046 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002047 !Elts[0]->getType()->isFloatingPointTy() &&
2048 !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002049 return Error(FirstEltLoc,
Nadav Rotem16087692011-12-05 06:29:09 +00002050 "vector elements must have integer, pointer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002051
Chris Lattnerdf986172009-01-02 07:01:27 +00002052 // Verify that all the vector elements have the same type.
2053 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2054 if (Elts[i]->getType() != Elts[0]->getType())
2055 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002056 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002057 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002058
Chris Lattner2ca5c862011-02-15 00:14:00 +00002059 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002060 ID.Kind = ValID::t_Constant;
2061 return false;
2062 }
2063 case lltok::lsquare: { // Array Constant
2064 Lex.Lex();
2065 SmallVector<Constant*, 16> Elts;
2066 LocTy FirstEltLoc = Lex.getLoc();
2067 if (ParseGlobalValueVector(Elts) ||
2068 ParseToken(lltok::rsquare, "expected end of array constant"))
2069 return true;
2070
2071 // Handle empty element.
2072 if (Elts.empty()) {
2073 // Use undef instead of an array because it's inconvenient to determine
2074 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002075 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002076 return false;
2077 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002078
Chris Lattnerdf986172009-01-02 07:01:27 +00002079 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002080 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002081 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002082
Owen Andersondebcb012009-07-29 22:17:13 +00002083 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002084
Chris Lattnerdf986172009-01-02 07:01:27 +00002085 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002086 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002087 if (Elts[i]->getType() != Elts[0]->getType())
2088 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002089 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002090 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002092
Jay Foad26701082011-06-22 09:24:39 +00002093 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002094 ID.Kind = ValID::t_Constant;
2095 return false;
2096 }
2097 case lltok::kw_c: // c "foo"
2098 Lex.Lex();
Chris Lattner18c7f802012-02-05 02:29:43 +00002099 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2100 false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002101 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2102 ID.Kind = ValID::t_Constant;
2103 return false;
2104
2105 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002106 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
Chad Rosier581600b2012-09-05 19:00:49 +00002107 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerdf986172009-01-02 07:01:27 +00002108 Lex.Lex();
2109 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002110 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosier581600b2012-09-05 19:00:49 +00002111 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002112 ParseStringConstant(ID.StrVal) ||
2113 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002114 ParseToken(lltok::StringConstant, "expected constraint string"))
2115 return true;
2116 ID.StrVal2 = Lex.getStrVal();
Chad Rosier36547342012-09-05 00:08:17 +00002117 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosier581600b2012-09-05 19:00:49 +00002118 (unsigned(AsmDialect)<<2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002119 ID.Kind = ValID::t_InlineAsm;
2120 return false;
2121 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002122
Chris Lattner09d9ef42009-10-28 03:39:23 +00002123 case lltok::kw_blockaddress: {
2124 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2125 Lex.Lex();
2126
2127 ValID Fn, Label;
2128 LocTy FnLoc, LabelLoc;
2129
2130 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2131 ParseValID(Fn) ||
2132 ParseToken(lltok::comma, "expected comma in block address expression")||
2133 ParseValID(Label) ||
2134 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2135 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002136
Chris Lattner09d9ef42009-10-28 03:39:23 +00002137 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2138 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002139 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002140 return Error(Label.Loc, "expected basic block name in blockaddress");
2141
2142 // Make a global variable as a placeholder for this reference.
2143 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2144 false, GlobalValue::InternalLinkage,
2145 0, "");
2146 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2147 ID.ConstantVal = FwdRef;
2148 ID.Kind = ValID::t_Constant;
2149 return false;
2150 }
2151
Chris Lattnerdf986172009-01-02 07:01:27 +00002152 case lltok::kw_trunc:
2153 case lltok::kw_zext:
2154 case lltok::kw_sext:
2155 case lltok::kw_fptrunc:
2156 case lltok::kw_fpext:
2157 case lltok::kw_bitcast:
2158 case lltok::kw_uitofp:
2159 case lltok::kw_sitofp:
2160 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002161 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002162 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002163 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002164 unsigned Opc = Lex.getUIntVal();
Chris Lattner1afcace2011-07-09 17:41:24 +00002165 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002166 Constant *SrcVal;
2167 Lex.Lex();
2168 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2169 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002170 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002171 ParseType(DestTy) ||
2172 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2173 return true;
2174 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2175 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002176 getTypeString(SrcVal->getType()) + "' to '" +
2177 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002178 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002179 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002180 ID.Kind = ValID::t_Constant;
2181 return false;
2182 }
2183 case lltok::kw_extractvalue: {
2184 Lex.Lex();
2185 Constant *Val;
2186 SmallVector<unsigned, 4> Indices;
2187 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2188 ParseGlobalTypeAndValue(Val) ||
2189 ParseIndexList(Indices) ||
2190 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2191 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002192
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002193 if (!Val->getType()->isAggregateType())
2194 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002195 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002196 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002197 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002198 ID.Kind = ValID::t_Constant;
2199 return false;
2200 }
2201 case lltok::kw_insertvalue: {
2202 Lex.Lex();
2203 Constant *Val0, *Val1;
2204 SmallVector<unsigned, 4> Indices;
2205 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2206 ParseGlobalTypeAndValue(Val0) ||
2207 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2208 ParseGlobalTypeAndValue(Val1) ||
2209 ParseIndexList(Indices) ||
2210 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2211 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002212 if (!Val0->getType()->isAggregateType())
2213 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002214 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002215 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002216 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002217 ID.Kind = ValID::t_Constant;
2218 return false;
2219 }
2220 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002221 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002222 unsigned PredVal, Opc = Lex.getUIntVal();
2223 Constant *Val0, *Val1;
2224 Lex.Lex();
2225 if (ParseCmpPredicate(PredVal, Opc) ||
2226 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2227 ParseGlobalTypeAndValue(Val0) ||
2228 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2229 ParseGlobalTypeAndValue(Val1) ||
2230 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2231 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002232
Chris Lattnerdf986172009-01-02 07:01:27 +00002233 if (Val0->getType() != Val1->getType())
2234 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002235
Chris Lattnerdf986172009-01-02 07:01:27 +00002236 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002237
Chris Lattnerdf986172009-01-02 07:01:27 +00002238 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002239 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002240 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002241 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002242 } else {
2243 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002244 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002245 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002246 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002247 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002248 }
2249 ID.Kind = ValID::t_Constant;
2250 return false;
2251 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002252
Chris Lattnerdf986172009-01-02 07:01:27 +00002253 // Binary Operators.
2254 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002255 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002256 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002257 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002258 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002259 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002260 case lltok::kw_udiv:
2261 case lltok::kw_sdiv:
2262 case lltok::kw_fdiv:
2263 case lltok::kw_urem:
2264 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002265 case lltok::kw_frem:
2266 case lltok::kw_shl:
2267 case lltok::kw_lshr:
2268 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002269 bool NUW = false;
2270 bool NSW = false;
2271 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002272 unsigned Opc = Lex.getUIntVal();
2273 Constant *Val0, *Val1;
2274 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002275 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002276 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2277 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002278 if (EatIfPresent(lltok::kw_nuw))
2279 NUW = true;
2280 if (EatIfPresent(lltok::kw_nsw)) {
2281 NSW = true;
2282 if (EatIfPresent(lltok::kw_nuw))
2283 NUW = true;
2284 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002285 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2286 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002287 if (EatIfPresent(lltok::kw_exact))
2288 Exact = true;
2289 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002290 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2291 ParseGlobalTypeAndValue(Val0) ||
2292 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2293 ParseGlobalTypeAndValue(Val1) ||
2294 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2295 return true;
2296 if (Val0->getType() != Val1->getType())
2297 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002298 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002299 if (NUW)
2300 return Error(ModifierLoc, "nuw only applies to integer operations");
2301 if (NSW)
2302 return Error(ModifierLoc, "nsw only applies to integer operations");
2303 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002304 // Check that the type is valid for the operator.
2305 switch (Opc) {
2306 case Instruction::Add:
2307 case Instruction::Sub:
2308 case Instruction::Mul:
2309 case Instruction::UDiv:
2310 case Instruction::SDiv:
2311 case Instruction::URem:
2312 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002313 case Instruction::Shl:
2314 case Instruction::AShr:
2315 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002316 if (!Val0->getType()->isIntOrIntVectorTy())
2317 return Error(ID.Loc, "constexpr requires integer operands");
2318 break;
2319 case Instruction::FAdd:
2320 case Instruction::FSub:
2321 case Instruction::FMul:
2322 case Instruction::FDiv:
2323 case Instruction::FRem:
2324 if (!Val0->getType()->isFPOrFPVectorTy())
2325 return Error(ID.Loc, "constexpr requires fp operands");
2326 break;
2327 default: llvm_unreachable("Unknown binary operator!");
2328 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002329 unsigned Flags = 0;
2330 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2331 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002332 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002333 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002334 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002335 ID.Kind = ValID::t_Constant;
2336 return false;
2337 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002338
Chris Lattnerdf986172009-01-02 07:01:27 +00002339 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002340 case lltok::kw_and:
2341 case lltok::kw_or:
2342 case lltok::kw_xor: {
2343 unsigned Opc = Lex.getUIntVal();
2344 Constant *Val0, *Val1;
2345 Lex.Lex();
2346 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2347 ParseGlobalTypeAndValue(Val0) ||
2348 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2349 ParseGlobalTypeAndValue(Val1) ||
2350 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2351 return true;
2352 if (Val0->getType() != Val1->getType())
2353 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002354 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002355 return Error(ID.Loc,
2356 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002357 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002358 ID.Kind = ValID::t_Constant;
2359 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002360 }
2361
Chris Lattnerdf986172009-01-02 07:01:27 +00002362 case lltok::kw_getelementptr:
2363 case lltok::kw_shufflevector:
2364 case lltok::kw_insertelement:
2365 case lltok::kw_extractelement:
2366 case lltok::kw_select: {
2367 unsigned Opc = Lex.getUIntVal();
2368 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002369 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002370 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002371 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002372 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002373 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2374 ParseGlobalValueVector(Elts) ||
2375 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2376 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002377
Chris Lattnerdf986172009-01-02 07:01:27 +00002378 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem16087692011-12-05 06:29:09 +00002379 if (Elts.size() == 0 ||
2380 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002381 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002382
Jay Foaddab3d292011-07-21 14:31:17 +00002383 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foada9203102011-07-25 09:48:08 +00002384 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002385 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad4b5e2072011-07-21 15:15:37 +00002386 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2387 InBounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002388 } else if (Opc == Instruction::Select) {
2389 if (Elts.size() != 3)
2390 return Error(ID.Loc, "expected three operands to select");
2391 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2392 Elts[2]))
2393 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002394 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002395 } else if (Opc == Instruction::ShuffleVector) {
2396 if (Elts.size() != 3)
2397 return Error(ID.Loc, "expected three operands to shufflevector");
2398 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2399 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002400 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002401 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002402 } else if (Opc == Instruction::ExtractElement) {
2403 if (Elts.size() != 2)
2404 return Error(ID.Loc, "expected two operands to extractelement");
2405 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2406 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002407 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002408 } else {
2409 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2410 if (Elts.size() != 3)
2411 return Error(ID.Loc, "expected three operands to insertelement");
2412 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2413 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002414 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002415 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002416 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002417
Chris Lattnerdf986172009-01-02 07:01:27 +00002418 ID.Kind = ValID::t_Constant;
2419 return false;
2420 }
2421 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002422
Chris Lattnerdf986172009-01-02 07:01:27 +00002423 Lex.Lex();
2424 return false;
2425}
2426
2427/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002428bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez92f238d2010-01-11 22:31:58 +00002429 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002430 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002431 Value *V = NULL;
2432 bool Parsed = ParseValID(ID) ||
2433 ConvertValIDToValue(Ty, ID, V, NULL);
2434 if (V && !(C = dyn_cast<Constant>(V)))
2435 return Error(ID.Loc, "global values must be constants");
2436 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002437}
2438
Victor Hernandez92f238d2010-01-11 22:31:58 +00002439bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002440 Type *Ty = 0;
2441 return ParseType(Ty) ||
2442 ParseGlobalValue(Ty, V);
Victor Hernandez92f238d2010-01-11 22:31:58 +00002443}
2444
2445/// ParseGlobalValueVector
2446/// ::= /*empty*/
2447/// ::= TypeAndValue (',' TypeAndValue)*
2448bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2449 // Empty list.
2450 if (Lex.getKind() == lltok::rbrace ||
2451 Lex.getKind() == lltok::rsquare ||
2452 Lex.getKind() == lltok::greater ||
2453 Lex.getKind() == lltok::rparen)
2454 return false;
2455
2456 Constant *C;
2457 if (ParseGlobalTypeAndValue(C)) return true;
2458 Elts.push_back(C);
2459
2460 while (EatIfPresent(lltok::comma)) {
2461 if (ParseGlobalTypeAndValue(C)) return true;
2462 Elts.push_back(C);
2463 }
2464
2465 return false;
2466}
2467
Dan Gohman309b3af2010-08-24 02:24:03 +00002468bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2469 assert(Lex.getKind() == lltok::lbrace);
2470 Lex.Lex();
2471
2472 SmallVector<Value*, 16> Elts;
2473 if (ParseMDNodeVector(Elts, PFS) ||
2474 ParseToken(lltok::rbrace, "expected end of metadata node"))
2475 return true;
2476
Jay Foadec9186b2011-04-21 19:59:31 +00002477 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002478 ID.Kind = ValID::t_MDNode;
2479 return false;
2480}
2481
Dan Gohman83448032010-07-14 18:26:50 +00002482/// ParseMetadataValue
2483/// ::= !42
2484/// ::= !{...}
2485/// ::= !"string"
2486bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2487 assert(Lex.getKind() == lltok::exclaim);
2488 Lex.Lex();
2489
2490 // MDNode:
2491 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002492 if (Lex.getKind() == lltok::lbrace)
2493 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002494
2495 // Standalone metadata reference
2496 // !42
2497 if (Lex.getKind() == lltok::APSInt) {
2498 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2499 ID.Kind = ValID::t_MDNode;
2500 return false;
2501 }
2502
2503 // MDString:
2504 // ::= '!' STRINGCONSTANT
2505 if (ParseMDString(ID.MDStringVal)) return true;
2506 ID.Kind = ValID::t_MDString;
2507 return false;
2508}
2509
Victor Hernandez92f238d2010-01-11 22:31:58 +00002510
2511//===----------------------------------------------------------------------===//
2512// Function Parsing.
2513//===----------------------------------------------------------------------===//
2514
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002515bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez92f238d2010-01-11 22:31:58 +00002516 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002517 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002518 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002519
Chris Lattnerdf986172009-01-02 07:01:27 +00002520 switch (ID.Kind) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002521 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002522 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2523 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2524 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002525 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002526 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2527 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2528 return (V == 0);
2529 case ValID::t_InlineAsm: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002530 PointerType *PTy = dyn_cast<PointerType>(Ty);
2531 FunctionType *FTy =
Victor Hernandez92f238d2010-01-11 22:31:58 +00002532 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2533 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2534 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosier36547342012-09-05 00:08:17 +00002535 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosier581600b2012-09-05 19:00:49 +00002536 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez92f238d2010-01-11 22:31:58 +00002537 return false;
2538 }
2539 case ValID::t_MDNode:
2540 if (!Ty->isMetadataTy())
2541 return Error(ID.Loc, "metadata value must have metadata type");
2542 V = ID.MDNodeVal;
2543 return false;
2544 case ValID::t_MDString:
2545 if (!Ty->isMetadataTy())
2546 return Error(ID.Loc, "metadata value must have metadata type");
2547 V = ID.MDStringVal;
2548 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002549 case ValID::t_GlobalName:
2550 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2551 return V == 0;
2552 case ValID::t_GlobalID:
2553 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2554 return V == 0;
2555 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002556 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002557 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002558 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002559 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002560 return false;
2561 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002562 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002563 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2564 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002565
Dan Gohmance163392011-12-17 00:04:22 +00002566 // The lexer has no type info, so builds all half, float, and double FP
2567 // constants as double. Fix this here. Long double does not need this.
2568 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002569 bool Ignored;
Dan Gohmance163392011-12-17 00:04:22 +00002570 if (Ty->isHalfTy())
2571 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2572 &Ignored);
2573 else if (Ty->isFloatTy())
2574 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2575 &Ignored);
Chris Lattnerdf986172009-01-02 07:01:27 +00002576 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002577 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002578
Chris Lattner959873d2009-01-05 18:24:23 +00002579 if (V->getType() != Ty)
2580 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002581 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002582
Chris Lattnerdf986172009-01-02 07:01:27 +00002583 return false;
2584 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002585 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002586 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002587 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002588 return false;
2589 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002590 // FIXME: LabelTy should not be a first-class type.
Chris Lattner1afcace2011-07-09 17:41:24 +00002591 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002592 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002593 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002594 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002595 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002596 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002597 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002598 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002599 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002600 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002601 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002602 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002603 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002604 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002605 return false;
2606 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002607 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002608 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002609
Chris Lattnerdf986172009-01-02 07:01:27 +00002610 V = ID.ConstantVal;
2611 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +00002612 case ValID::t_ConstantStruct:
2613 case ValID::t_PackedConstantStruct:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002614 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002615 if (ST->getNumElements() != ID.UIntVal)
2616 return Error(ID.Loc,
2617 "initializer with struct type has wrong # elements");
2618 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2619 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2620
2621 // Verify that the elements are compatible with the structtype.
2622 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2623 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2624 return Error(ID.Loc, "element " + Twine(i) +
2625 " of struct initializer doesn't match struct element type");
2626
Frits van Bommel39b5abf2011-07-18 12:00:32 +00002627 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2628 ID.UIntVal));
Chris Lattner1afcace2011-07-09 17:41:24 +00002629 } else
2630 return Error(ID.Loc, "constant expression type mismatch");
2631 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002632 }
Chandler Carruth732f05c2012-01-10 18:08:01 +00002633 llvm_unreachable("Invalid ValID");
Chris Lattnerdf986172009-01-02 07:01:27 +00002634}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002635
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002636bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002637 V = 0;
2638 ValID ID;
Chris Lattner1afcace2011-07-09 17:41:24 +00002639 return ParseValID(ID, PFS) ||
2640 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002641}
2642
Chris Lattner1afcace2011-07-09 17:41:24 +00002643bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2644 Type *Ty = 0;
2645 return ParseType(Ty) ||
2646 ParseValue(Ty, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002647}
2648
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002649bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2650 PerFunctionState &PFS) {
2651 Value *V;
2652 Loc = Lex.getLoc();
2653 if (ParseTypeAndValue(V, PFS)) return true;
2654 if (!isa<BasicBlock>(V))
2655 return Error(Loc, "expected a basic block");
2656 BB = cast<BasicBlock>(V);
2657 return false;
2658}
2659
2660
Chris Lattnerdf986172009-01-02 07:01:27 +00002661/// FunctionHeader
2662/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002663/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002664/// OptionalAlign OptGC
2665bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2666 // Parse the linkage.
2667 LocTy LinkageLoc = Lex.getLoc();
2668 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002669
Kostya Serebryany164b86b2012-01-20 17:56:17 +00002670 unsigned Visibility;
2671 Attributes RetAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002672 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00002673 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002674 LocTy RetTypeLoc = Lex.getLoc();
2675 if (ParseOptionalLinkage(Linkage) ||
2676 ParseOptionalVisibility(Visibility) ||
2677 ParseOptionalCallingConv(CC) ||
2678 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002679 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002680 return true;
2681
2682 // Verify that the linkage is ok.
2683 switch ((GlobalValue::LinkageTypes)Linkage) {
2684 case GlobalValue::ExternalLinkage:
2685 break; // always ok.
2686 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002687 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002688 if (isDefine)
2689 return Error(LinkageLoc, "invalid linkage for function definition");
2690 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002691 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002692 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002693 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002694 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002695 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002696 case GlobalValue::LinkOnceAnyLinkage:
2697 case GlobalValue::LinkOnceODRLinkage:
Bill Wendling32811be2012-08-17 18:33:14 +00002698 case GlobalValue::LinkOnceODRAutoHideLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002699 case GlobalValue::WeakAnyLinkage:
2700 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002701 case GlobalValue::DLLExportLinkage:
2702 if (!isDefine)
2703 return Error(LinkageLoc, "invalid linkage for function declaration");
2704 break;
2705 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002706 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002707 return Error(LinkageLoc, "invalid function linkage type");
2708 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002709
Chris Lattner1afcace2011-07-09 17:41:24 +00002710 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002711 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002712
Chris Lattnerdf986172009-01-02 07:01:27 +00002713 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002714
2715 std::string FunctionName;
2716 if (Lex.getKind() == lltok::GlobalVar) {
2717 FunctionName = Lex.getStrVal();
2718 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2719 unsigned NameID = Lex.getUIntVal();
2720
2721 if (NameID != NumberedVals.size())
2722 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002723 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002724 } else {
2725 return TokError("expected function name");
2726 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002727
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002728 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002729
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002730 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002731 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002732
Chris Lattner1afcace2011-07-09 17:41:24 +00002733 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002734 bool isVarArg;
Kostya Serebryany164b86b2012-01-20 17:56:17 +00002735 Attributes FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002736 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002737 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002738 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002739 bool UnnamedAddr;
2740 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002741
Chris Lattner1afcace2011-07-09 17:41:24 +00002742 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002743 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2744 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002745 ParseOptionalAttrs(FuncAttrs, 2) ||
2746 (EatIfPresent(lltok::kw_section) &&
2747 ParseStringConstant(Section)) ||
2748 ParseOptionalAlignment(Alignment) ||
2749 (EatIfPresent(lltok::kw_gc) &&
2750 ParseStringConstant(GC)))
2751 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002752
2753 // If the alignment was parsed as an attribute, move to the alignment field.
2754 if (FuncAttrs & Attribute::Alignment) {
Bill Wendlingef99fe82012-09-21 15:26:31 +00002755 Alignment = FuncAttrs.getAlignment();
Chris Lattnerdf986172009-01-02 07:01:27 +00002756 FuncAttrs &= ~Attribute::Alignment;
2757 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002758
Chris Lattnerdf986172009-01-02 07:01:27 +00002759 // Okay, if we got here, the function is syntactically valid. Convert types
2760 // and do semantic checks.
Jay Foad5fdd6c82011-07-12 14:06:48 +00002761 std::vector<Type*> ParamTypeList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002762 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002763
Bill Wendlinge603fe42012-09-19 23:54:18 +00002764 if (RetAttrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00002765 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002766
Chris Lattnerdf986172009-01-02 07:01:27 +00002767 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002768 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlinge603fe42012-09-19 23:54:18 +00002769 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00002770 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2771 }
2772
Bill Wendlinge603fe42012-09-19 23:54:18 +00002773 if (FuncAttrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00002774 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2775
Chris Lattnerd509d0b2012-05-28 01:47:44 +00002776 AttrListPtr PAL = AttrListPtr::get(Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002777
Benjamin Kramerf0127052010-01-05 13:12:22 +00002778 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002779 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2780
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002781 FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002782 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002783 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002784
2785 Fn = 0;
2786 if (!FunctionName.empty()) {
2787 // If this was a definition of a forward reference, remove the definition
2788 // from the forward reference table and fill in the forward ref.
2789 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2790 ForwardRefVals.find(FunctionName);
2791 if (FRVI != ForwardRefVals.end()) {
2792 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002793 if (Fn->getType() != PFT)
2794 return Error(FRVI->second.second, "invalid forward reference to "
2795 "function '" + FunctionName + "' with wrong type!");
2796
Chris Lattnerdf986172009-01-02 07:01:27 +00002797 ForwardRefVals.erase(FRVI);
2798 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002799 // Reject redefinitions.
2800 return Error(NameLoc, "invalid redefinition of function '" +
2801 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002802 } else if (M->getNamedValue(FunctionName)) {
2803 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002804 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002805
Dan Gohman41905542009-08-29 23:37:49 +00002806 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002807 // If this is a definition of a forward referenced function, make sure the
2808 // types agree.
2809 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2810 = ForwardRefValIDs.find(NumberedVals.size());
2811 if (I != ForwardRefValIDs.end()) {
2812 Fn = cast<Function>(I->second.first);
2813 if (Fn->getType() != PFT)
2814 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002815 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002816 ForwardRefValIDs.erase(I);
2817 }
2818 }
2819
2820 if (Fn == 0)
2821 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2822 else // Move the forward-reference to the correct spot in the module.
2823 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2824
2825 if (FunctionName.empty())
2826 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002827
Chris Lattnerdf986172009-01-02 07:01:27 +00002828 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2829 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2830 Fn->setCallingConv(CC);
2831 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002832 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002833 Fn->setAlignment(Alignment);
2834 Fn->setSection(Section);
2835 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002836
Chris Lattnerdf986172009-01-02 07:01:27 +00002837 // Add all of the arguments we parsed to the function.
2838 Function::arg_iterator ArgIt = Fn->arg_begin();
2839 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2840 // If the argument has a name, insert it into the argument symbol table.
2841 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002842
Chris Lattnerdf986172009-01-02 07:01:27 +00002843 // Set the name, if it conflicted, it will be auto-renamed.
2844 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002845
Benjamin Krameraf812352010-10-16 11:28:23 +00002846 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002847 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2848 ArgList[i].Name + "'");
2849 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002850
Chris Lattnerdf986172009-01-02 07:01:27 +00002851 return false;
2852}
2853
2854
2855/// ParseFunctionBody
2856/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002857///
2858bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002859 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002860 return TokError("expected '{' in function body");
2861 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002862
Chris Lattner09d9ef42009-10-28 03:39:23 +00002863 int FunctionNumber = -1;
2864 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2865
2866 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002867
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002868 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002869 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002870 return TokError("function body requires at least one basic block");
2871
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002872 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002873 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002874
Chris Lattnerdf986172009-01-02 07:01:27 +00002875 // Eat the }.
2876 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002877
Chris Lattnerdf986172009-01-02 07:01:27 +00002878 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002879 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002880}
2881
2882/// ParseBasicBlock
2883/// ::= LabelStr? Instruction*
2884bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2885 // If this basic block starts out with a name, remember it.
2886 std::string Name;
2887 LocTy NameLoc = Lex.getLoc();
2888 if (Lex.getKind() == lltok::LabelStr) {
2889 Name = Lex.getStrVal();
2890 Lex.Lex();
2891 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002892
Chris Lattnerdf986172009-01-02 07:01:27 +00002893 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2894 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002895
Chris Lattnerdf986172009-01-02 07:01:27 +00002896 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002897
Chris Lattnerdf986172009-01-02 07:01:27 +00002898 // Parse the instructions in this block until we get a terminator.
2899 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002900 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002901 do {
2902 // This instruction may have three possibilities for a name: a) none
2903 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2904 LocTy NameLoc = Lex.getLoc();
2905 int NameID = -1;
2906 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002907
Chris Lattnerdf986172009-01-02 07:01:27 +00002908 if (Lex.getKind() == lltok::LocalVarID) {
2909 NameID = Lex.getUIntVal();
2910 Lex.Lex();
2911 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2912 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002913 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002914 NameStr = Lex.getStrVal();
2915 Lex.Lex();
2916 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2917 return true;
2918 }
Devang Patelf633a062009-09-17 23:04:48 +00002919
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002920 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Topper85814382012-02-07 05:05:23 +00002921 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002922 case InstError: return true;
2923 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002924 BB->getInstList().push_back(Inst);
2925
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002926 // With a normal result, we check to see if the instruction is followed by
2927 // a comma and metadata.
2928 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002929 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002930 return true;
2931 break;
2932 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002933 BB->getInstList().push_back(Inst);
2934
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002935 // If the instruction parser ate an extra comma at the end of it, it
2936 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002937 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002938 return true;
2939 break;
2940 }
Devang Patelf633a062009-09-17 23:04:48 +00002941
Chris Lattnerdf986172009-01-02 07:01:27 +00002942 // Set the name on the instruction.
2943 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2944 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002945
Chris Lattnerdf986172009-01-02 07:01:27 +00002946 return false;
2947}
2948
2949//===----------------------------------------------------------------------===//
2950// Instruction Parsing.
2951//===----------------------------------------------------------------------===//
2952
2953/// ParseInstruction - Parse one of the many different instructions.
2954///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002955int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2956 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002957 lltok::Kind Token = Lex.getKind();
2958 if (Token == lltok::Eof)
2959 return TokError("found end of file when expecting more instructions");
2960 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002961 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002962 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002963
Chris Lattnerdf986172009-01-02 07:01:27 +00002964 switch (Token) {
2965 default: return Error(Loc, "expected instruction opcode");
2966 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002967 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002968 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2969 case lltok::kw_br: return ParseBr(Inst, PFS);
2970 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002971 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002972 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002973 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002974 // Binary Operators.
2975 case lltok::kw_add:
2976 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00002977 case lltok::kw_mul:
2978 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00002979 bool NUW = EatIfPresent(lltok::kw_nuw);
2980 bool NSW = EatIfPresent(lltok::kw_nsw);
2981 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2982
2983 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2984
2985 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2986 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2987 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002988 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002989 case lltok::kw_fadd:
2990 case lltok::kw_fsub:
2991 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2992
Chris Lattner35bda892011-02-06 21:44:57 +00002993 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00002994 case lltok::kw_udiv:
2995 case lltok::kw_lshr:
2996 case lltok::kw_ashr: {
2997 bool Exact = EatIfPresent(lltok::kw_exact);
2998
2999 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3000 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3001 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00003002 }
3003
Chris Lattnerdf986172009-01-02 07:01:27 +00003004 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003005 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003006 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003007 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003008 case lltok::kw_and:
3009 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003010 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003011 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003012 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003013 // Casts.
3014 case lltok::kw_trunc:
3015 case lltok::kw_zext:
3016 case lltok::kw_sext:
3017 case lltok::kw_fptrunc:
3018 case lltok::kw_fpext:
3019 case lltok::kw_bitcast:
3020 case lltok::kw_uitofp:
3021 case lltok::kw_sitofp:
3022 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003023 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003024 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003025 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003026 // Other.
3027 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003028 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003029 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3030 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3031 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3032 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlinge6e88262011-08-12 20:24:12 +00003033 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003034 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3035 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3036 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003037 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003038 case lltok::kw_load: return ParseLoad(Inst, PFS);
3039 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedmanf03bb262011-08-12 22:50:01 +00003040 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3041 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedman47f35132011-07-25 23:16:38 +00003042 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003043 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3044 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3045 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3046 }
3047}
3048
3049/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3050bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003051 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003052 switch (Lex.getKind()) {
3053 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3054 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3055 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3056 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3057 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3058 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3059 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3060 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3061 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3062 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3063 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3064 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3065 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3066 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3067 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3068 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3069 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3070 }
3071 } else {
3072 switch (Lex.getKind()) {
3073 default: TokError("expected icmp predicate (e.g. 'eq')");
3074 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3075 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3076 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3077 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3078 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3079 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3080 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3081 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3082 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3083 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3084 }
3085 }
3086 Lex.Lex();
3087 return false;
3088}
3089
3090//===----------------------------------------------------------------------===//
3091// Terminator Instructions.
3092//===----------------------------------------------------------------------===//
3093
3094/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003095/// ::= 'ret' void (',' !dbg, !1)*
3096/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003097bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattner1afcace2011-07-09 17:41:24 +00003098 PerFunctionState &PFS) {
3099 SMLoc TypeLoc = Lex.getLoc();
3100 Type *Ty = 0;
Chris Lattnera9a9e072009-03-09 04:49:14 +00003101 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003102
Chris Lattner1afcace2011-07-09 17:41:24 +00003103 Type *ResType = PFS.getFunction().getReturnType();
3104
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003105 if (Ty->isVoidTy()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003106 if (!ResType->isVoidTy())
3107 return Error(TypeLoc, "value doesn't match function result type '" +
3108 getTypeString(ResType) + "'");
3109
Owen Anderson1d0be152009-08-13 21:58:54 +00003110 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003111 return false;
3112 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003113
Chris Lattnerdf986172009-01-02 07:01:27 +00003114 Value *RV;
3115 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003116
Chris Lattner1afcace2011-07-09 17:41:24 +00003117 if (ResType != RV->getType())
3118 return Error(TypeLoc, "value doesn't match function result type '" +
3119 getTypeString(ResType) + "'");
3120
Owen Anderson1d0be152009-08-13 21:58:54 +00003121 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003122 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003123}
3124
3125
3126/// ParseBr
3127/// ::= 'br' TypeAndValue
3128/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3129bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3130 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003131 Value *Op0;
3132 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003133 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003134
Chris Lattnerdf986172009-01-02 07:01:27 +00003135 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3136 Inst = BranchInst::Create(BB);
3137 return false;
3138 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003139
Owen Anderson1d0be152009-08-13 21:58:54 +00003140 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003141 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003142
Chris Lattnerdf986172009-01-02 07:01:27 +00003143 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003144 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003145 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003146 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003147 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003148
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003149 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003150 return false;
3151}
3152
3153/// ParseSwitch
3154/// Instruction
3155/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3156/// JumpTable
3157/// ::= (TypeAndValue ',' TypeAndValue)*
3158bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3159 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003160 Value *Cond;
3161 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003162 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3163 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003164 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003165 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3166 return true;
3167
Duncan Sands1df98592010-02-16 11:11:14 +00003168 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003169 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003170
Chris Lattnerdf986172009-01-02 07:01:27 +00003171 // Parse the jump table pairs.
3172 SmallPtrSet<Value*, 32> SeenCases;
3173 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3174 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003175 Value *Constant;
3176 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003177
Chris Lattnerdf986172009-01-02 07:01:27 +00003178 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3179 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003180 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003181 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003182
Chris Lattnerdf986172009-01-02 07:01:27 +00003183 if (!SeenCases.insert(Constant))
3184 return Error(CondLoc, "duplicate case value in switch");
3185 if (!isa<ConstantInt>(Constant))
3186 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003187
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003188 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003189 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003190
Chris Lattnerdf986172009-01-02 07:01:27 +00003191 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003192
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003193 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003194 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3195 SI->addCase(Table[i].first, Table[i].second);
3196 Inst = SI;
3197 return false;
3198}
3199
Chris Lattnerab21db72009-10-28 00:19:10 +00003200/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003201/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003202/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3203bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003204 LocTy AddrLoc;
3205 Value *Address;
3206 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003207 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3208 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003209 return true;
3210
Duncan Sands1df98592010-02-16 11:11:14 +00003211 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003212 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003213
3214 // Parse the destination list.
3215 SmallVector<BasicBlock*, 16> DestList;
3216
3217 if (Lex.getKind() != lltok::rsquare) {
3218 BasicBlock *DestBB;
3219 if (ParseTypeAndBasicBlock(DestBB, PFS))
3220 return true;
3221 DestList.push_back(DestBB);
3222
3223 while (EatIfPresent(lltok::comma)) {
3224 if (ParseTypeAndBasicBlock(DestBB, PFS))
3225 return true;
3226 DestList.push_back(DestBB);
3227 }
3228 }
3229
3230 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3231 return true;
3232
Chris Lattnerab21db72009-10-28 00:19:10 +00003233 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003234 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3235 IBI->addDestination(DestList[i]);
3236 Inst = IBI;
3237 return false;
3238}
3239
3240
Chris Lattnerdf986172009-01-02 07:01:27 +00003241/// ParseInvoke
3242/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3243/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3244bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3245 LocTy CallLoc = Lex.getLoc();
Kostya Serebryany164b86b2012-01-20 17:56:17 +00003246 Attributes RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003247 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003248 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003249 LocTy RetTypeLoc;
3250 ValID CalleeID;
3251 SmallVector<ParamInfo, 16> ArgList;
3252
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003253 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003254 if (ParseOptionalCallingConv(CC) ||
3255 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003256 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003257 ParseValID(CalleeID) ||
3258 ParseParameterList(ArgList, PFS) ||
3259 ParseOptionalAttrs(FnAttrs, 2) ||
3260 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003261 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003262 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003263 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003264 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003265
Chris Lattnerdf986172009-01-02 07:01:27 +00003266 // If RetType is a non-function pointer type, then this is the short syntax
3267 // for the call, which means that RetType is just the return type. Infer the
3268 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003269 PointerType *PFTy = 0;
3270 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003271 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3272 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3273 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003274 std::vector<Type*> ParamTypes;
Chris Lattnerdf986172009-01-02 07:01:27 +00003275 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3276 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003277
Chris Lattnerdf986172009-01-02 07:01:27 +00003278 if (!FunctionType::isValidReturnType(RetType))
3279 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003280
Owen Andersondebcb012009-07-29 22:17:13 +00003281 Ty = FunctionType::get(RetType, ParamTypes, false);
3282 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003283 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003284
Chris Lattnerdf986172009-01-02 07:01:27 +00003285 // Look up the callee.
3286 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003287 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003288
Chris Lattnerdf986172009-01-02 07:01:27 +00003289 // Set up the Attributes for the function.
3290 SmallVector<AttributeWithIndex, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003291 if (RetAttrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003292 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003293
Chris Lattnerdf986172009-01-02 07:01:27 +00003294 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003295
Chris Lattnerdf986172009-01-02 07:01:27 +00003296 // Loop through FunctionType's arguments and ensure they are specified
3297 // correctly. Also, gather any parameter attributes.
3298 FunctionType::param_iterator I = Ty->param_begin();
3299 FunctionType::param_iterator E = Ty->param_end();
3300 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003301 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003302 if (I != E) {
3303 ExpectedTy = *I++;
3304 } else if (!Ty->isVarArg()) {
3305 return Error(ArgList[i].Loc, "too many arguments specified");
3306 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003307
Chris Lattnerdf986172009-01-02 07:01:27 +00003308 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3309 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003310 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003311 Args.push_back(ArgList[i].V);
Bill Wendlinge603fe42012-09-19 23:54:18 +00003312 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003313 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3314 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003315
Chris Lattnerdf986172009-01-02 07:01:27 +00003316 if (I != E)
3317 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003318
Bill Wendlinge603fe42012-09-19 23:54:18 +00003319 if (FnAttrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003320 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003321
Chris Lattnerdf986172009-01-02 07:01:27 +00003322 // Finish off the Attributes and check them
Chris Lattnerd509d0b2012-05-28 01:47:44 +00003323 AttrListPtr PAL = AttrListPtr::get(Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003324
Jay Foada3efbb12011-07-15 08:37:34 +00003325 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003326 II->setCallingConv(CC);
3327 II->setAttributes(PAL);
3328 Inst = II;
3329 return false;
3330}
3331
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003332/// ParseResume
3333/// ::= 'resume' TypeAndValue
3334bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3335 Value *Exn; LocTy ExnLoc;
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003336 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3337 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003338
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003339 ResumeInst *RI = ResumeInst::Create(Exn);
3340 Inst = RI;
3341 return false;
3342}
Chris Lattnerdf986172009-01-02 07:01:27 +00003343
3344//===----------------------------------------------------------------------===//
3345// Binary Operators.
3346//===----------------------------------------------------------------------===//
3347
3348/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003349/// ::= ArithmeticOps TypeAndValue ',' Value
3350///
3351/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3352/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003353bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003354 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003355 LocTy Loc; Value *LHS, *RHS;
3356 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3357 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3358 ParseValue(LHS->getType(), RHS, PFS))
3359 return true;
3360
Chris Lattnere914b592009-01-05 08:24:46 +00003361 bool Valid;
3362 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003363 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003364 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003365 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3366 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003367 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003368 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3369 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003370 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003371
Chris Lattnere914b592009-01-05 08:24:46 +00003372 if (!Valid)
3373 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003374
Chris Lattnerdf986172009-01-02 07:01:27 +00003375 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3376 return false;
3377}
3378
3379/// ParseLogical
3380/// ::= ArithmeticOps TypeAndValue ',' Value {
3381bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3382 unsigned Opc) {
3383 LocTy Loc; Value *LHS, *RHS;
3384 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3385 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3386 ParseValue(LHS->getType(), RHS, PFS))
3387 return true;
3388
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003389 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003390 return Error(Loc,"instruction requires integer or integer vector operands");
3391
3392 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3393 return false;
3394}
3395
3396
3397/// ParseCompare
3398/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3399/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003400bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3401 unsigned Opc) {
3402 // Parse the integer/fp comparison predicate.
3403 LocTy Loc;
3404 unsigned Pred;
3405 Value *LHS, *RHS;
3406 if (ParseCmpPredicate(Pred, Opc) ||
3407 ParseTypeAndValue(LHS, Loc, PFS) ||
3408 ParseToken(lltok::comma, "expected ',' after compare value") ||
3409 ParseValue(LHS->getType(), RHS, PFS))
3410 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003411
Chris Lattnerdf986172009-01-02 07:01:27 +00003412 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003413 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003414 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003415 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003416 } else {
3417 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003418 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00003419 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003420 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003421 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003422 }
3423 return false;
3424}
3425
3426//===----------------------------------------------------------------------===//
3427// Other Instructions.
3428//===----------------------------------------------------------------------===//
3429
3430
3431/// ParseCast
3432/// ::= CastOpc TypeAndValue 'to' Type
3433bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3434 unsigned Opc) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003435 LocTy Loc;
3436 Value *Op;
3437 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003438 if (ParseTypeAndValue(Op, Loc, PFS) ||
3439 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3440 ParseType(DestTy))
3441 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003442
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003443 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3444 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003445 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003446 getTypeString(Op->getType()) + "' to '" +
3447 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003448 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003449 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3450 return false;
3451}
3452
3453/// ParseSelect
3454/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3455bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3456 LocTy Loc;
3457 Value *Op0, *Op1, *Op2;
3458 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3459 ParseToken(lltok::comma, "expected ',' after select condition") ||
3460 ParseTypeAndValue(Op1, PFS) ||
3461 ParseToken(lltok::comma, "expected ',' after select value") ||
3462 ParseTypeAndValue(Op2, PFS))
3463 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003464
Chris Lattnerdf986172009-01-02 07:01:27 +00003465 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3466 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003467
Chris Lattnerdf986172009-01-02 07:01:27 +00003468 Inst = SelectInst::Create(Op0, Op1, Op2);
3469 return false;
3470}
3471
Chris Lattner0088a5c2009-01-05 08:18:44 +00003472/// ParseVA_Arg
3473/// ::= 'va_arg' TypeAndValue ',' Type
3474bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003475 Value *Op;
Chris Lattner1afcace2011-07-09 17:41:24 +00003476 Type *EltTy = 0;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003477 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003478 if (ParseTypeAndValue(Op, PFS) ||
3479 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003480 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003481 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003482
Chris Lattner0088a5c2009-01-05 08:18:44 +00003483 if (!EltTy->isFirstClassType())
3484 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003485
3486 Inst = new VAArgInst(Op, EltTy);
3487 return false;
3488}
3489
3490/// ParseExtractElement
3491/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3492bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3493 LocTy Loc;
3494 Value *Op0, *Op1;
3495 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3496 ParseToken(lltok::comma, "expected ',' after extract value") ||
3497 ParseTypeAndValue(Op1, PFS))
3498 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003499
Chris Lattnerdf986172009-01-02 07:01:27 +00003500 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3501 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003502
Eric Christophera3500da2009-07-25 02:28:41 +00003503 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003504 return false;
3505}
3506
3507/// ParseInsertElement
3508/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3509bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3510 LocTy Loc;
3511 Value *Op0, *Op1, *Op2;
3512 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3513 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3514 ParseTypeAndValue(Op1, PFS) ||
3515 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3516 ParseTypeAndValue(Op2, PFS))
3517 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003518
Chris Lattnerdf986172009-01-02 07:01:27 +00003519 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003520 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003521
Chris Lattnerdf986172009-01-02 07:01:27 +00003522 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3523 return false;
3524}
3525
3526/// ParseShuffleVector
3527/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3528bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3529 LocTy Loc;
3530 Value *Op0, *Op1, *Op2;
3531 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3532 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3533 ParseTypeAndValue(Op1, PFS) ||
3534 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3535 ParseTypeAndValue(Op2, PFS))
3536 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003537
Chris Lattnerdf986172009-01-02 07:01:27 +00003538 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperaf393682012-02-01 23:43:12 +00003539 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003540
Chris Lattnerdf986172009-01-02 07:01:27 +00003541 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3542 return false;
3543}
3544
3545/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003546/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003547int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003548 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003549 Value *Op0, *Op1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003550
Chris Lattner1afcace2011-07-09 17:41:24 +00003551 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003552 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3553 ParseValue(Ty, Op0, PFS) ||
3554 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003555 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003556 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3557 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003558
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003559 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003560 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3561 while (1) {
3562 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003563
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003564 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003565 break;
3566
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003567 if (Lex.getKind() == lltok::MetadataVar) {
3568 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003569 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003570 }
Devang Patela43d46f2009-10-16 18:45:49 +00003571
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003572 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003573 ParseValue(Ty, Op0, PFS) ||
3574 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003575 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003576 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3577 return true;
3578 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003579
Chris Lattnerdf986172009-01-02 07:01:27 +00003580 if (!Ty->isFirstClassType())
3581 return Error(TypeLoc, "phi node must have first class type");
3582
Jay Foad3ecfc862011-03-30 11:28:46 +00003583 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003584 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3585 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3586 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003587 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003588}
3589
Bill Wendlinge6e88262011-08-12 20:24:12 +00003590/// ParseLandingPad
3591/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3592/// Clause
3593/// ::= 'catch' TypeAndValue
3594/// ::= 'filter'
3595/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3596bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3597 Type *Ty = 0; LocTy TyLoc;
3598 Value *PersFn; LocTy PersFnLoc;
Bill Wendlinge6e88262011-08-12 20:24:12 +00003599
3600 if (ParseType(Ty, TyLoc) ||
3601 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3602 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3603 return true;
3604
3605 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3606 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3607
3608 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3609 LandingPadInst::ClauseType CT;
3610 if (EatIfPresent(lltok::kw_catch))
3611 CT = LandingPadInst::Catch;
3612 else if (EatIfPresent(lltok::kw_filter))
3613 CT = LandingPadInst::Filter;
3614 else
3615 return TokError("expected 'catch' or 'filter' clause type");
3616
3617 Value *V; LocTy VLoc;
3618 if (ParseTypeAndValue(V, VLoc, PFS)) {
3619 delete LP;
3620 return true;
3621 }
3622
Bill Wendling746c8822011-08-12 20:52:25 +00003623 // A 'catch' type expects a non-array constant. A filter clause expects an
3624 // array constant.
3625 if (CT == LandingPadInst::Catch) {
3626 if (isa<ArrayType>(V->getType()))
3627 Error(VLoc, "'catch' clause has an invalid type");
3628 } else {
3629 if (!isa<ArrayType>(V->getType()))
3630 Error(VLoc, "'filter' clause has an invalid type");
3631 }
3632
Bill Wendlinge6e88262011-08-12 20:24:12 +00003633 LP->addClause(V);
3634 }
3635
3636 Inst = LP;
3637 return false;
3638}
3639
Chris Lattnerdf986172009-01-02 07:01:27 +00003640/// ParseCall
3641/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3642/// ParameterList OptionalAttrs
3643bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3644 bool isTail) {
Kostya Serebryany164b86b2012-01-20 17:56:17 +00003645 Attributes RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003646 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003647 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003648 LocTy RetTypeLoc;
3649 ValID CalleeID;
3650 SmallVector<ParamInfo, 16> ArgList;
3651 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003652
Chris Lattnerdf986172009-01-02 07:01:27 +00003653 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3654 ParseOptionalCallingConv(CC) ||
3655 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003656 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003657 ParseValID(CalleeID) ||
3658 ParseParameterList(ArgList, PFS) ||
3659 ParseOptionalAttrs(FnAttrs, 2))
3660 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003661
Chris Lattnerdf986172009-01-02 07:01:27 +00003662 // If RetType is a non-function pointer type, then this is the short syntax
3663 // for the call, which means that RetType is just the return type. Infer the
3664 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003665 PointerType *PFTy = 0;
3666 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003667 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3668 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3669 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003670 std::vector<Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003671 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3672 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003673
Chris Lattnerdf986172009-01-02 07:01:27 +00003674 if (!FunctionType::isValidReturnType(RetType))
3675 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003676
Owen Andersondebcb012009-07-29 22:17:13 +00003677 Ty = FunctionType::get(RetType, ParamTypes, false);
3678 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003679 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003680
Chris Lattnerdf986172009-01-02 07:01:27 +00003681 // Look up the callee.
3682 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003683 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003684
Chris Lattnerdf986172009-01-02 07:01:27 +00003685 // Set up the Attributes for the function.
3686 SmallVector<AttributeWithIndex, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003687 if (RetAttrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003688 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003689
Chris Lattnerdf986172009-01-02 07:01:27 +00003690 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003691
Chris Lattnerdf986172009-01-02 07:01:27 +00003692 // Loop through FunctionType's arguments and ensure they are specified
3693 // correctly. Also, gather any parameter attributes.
3694 FunctionType::param_iterator I = Ty->param_begin();
3695 FunctionType::param_iterator E = Ty->param_end();
3696 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003697 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003698 if (I != E) {
3699 ExpectedTy = *I++;
3700 } else if (!Ty->isVarArg()) {
3701 return Error(ArgList[i].Loc, "too many arguments specified");
3702 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003703
Chris Lattnerdf986172009-01-02 07:01:27 +00003704 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3705 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003706 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003707 Args.push_back(ArgList[i].V);
Bill Wendlinge603fe42012-09-19 23:54:18 +00003708 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003709 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3710 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003711
Chris Lattnerdf986172009-01-02 07:01:27 +00003712 if (I != E)
3713 return Error(CallLoc, "not enough parameters specified for call");
3714
Bill Wendlinge603fe42012-09-19 23:54:18 +00003715 if (FnAttrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003716 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3717
3718 // Finish off the Attributes and check them
Chris Lattnerd509d0b2012-05-28 01:47:44 +00003719 AttrListPtr PAL = AttrListPtr::get(Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003720
Jay Foada3efbb12011-07-15 08:37:34 +00003721 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003722 CI->setTailCall(isTail);
3723 CI->setCallingConv(CC);
3724 CI->setAttributes(PAL);
3725 Inst = CI;
3726 return false;
3727}
3728
3729//===----------------------------------------------------------------------===//
3730// Memory Instructions.
3731//===----------------------------------------------------------------------===//
3732
3733/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003734/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003735int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003736 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003737 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003738 unsigned Alignment = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00003739 Type *Ty = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003740 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003741
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003742 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003743 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003744 if (Lex.getKind() == lltok::kw_align) {
3745 if (ParseOptionalAlignment(Alignment)) return true;
3746 } else if (Lex.getKind() == lltok::MetadataVar) {
3747 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003748 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003749 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3750 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3751 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003752 }
3753 }
3754
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003755 if (Size && !Size->getType()->isIntegerTy())
3756 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003757
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003758 Inst = new AllocaInst(Ty, Size, Alignment);
3759 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003760}
3761
3762/// ParseLoad
Eli Friedmanf03bb262011-08-12 22:50:01 +00003763/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3764/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3765/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003766int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003767 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003768 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003769 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003770 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003771 AtomicOrdering Ordering = NotAtomic;
3772 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003773
3774 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003775 isAtomic = true;
3776 Lex.Lex();
3777 }
3778
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003779 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003780 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003781 isVolatile = true;
3782 Lex.Lex();
3783 }
3784
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003785 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003786 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003787 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3788 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003789
Duncan Sands1df98592010-02-16 11:11:14 +00003790 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003791 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3792 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman21006d42011-08-09 23:02:53 +00003793 if (isAtomic && !Alignment)
3794 return Error(Loc, "atomic load must have explicit non-zero alignment");
3795 if (Ordering == Release || Ordering == AcquireRelease)
3796 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003797
Eli Friedman21006d42011-08-09 23:02:53 +00003798 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003799 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003800}
3801
3802/// ParseStore
Eli Friedmanf03bb262011-08-12 22:50:01 +00003803
3804/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3805/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman21006d42011-08-09 23:02:53 +00003806/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003807int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003808 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003809 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003810 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003811 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003812 AtomicOrdering Ordering = NotAtomic;
3813 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003814
3815 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003816 isAtomic = true;
3817 Lex.Lex();
3818 }
3819
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003820 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003821 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003822 isVolatile = true;
3823 Lex.Lex();
3824 }
3825
Chris Lattnerdf986172009-01-02 07:01:27 +00003826 if (ParseTypeAndValue(Val, Loc, PFS) ||
3827 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003828 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003829 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003830 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003831 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003832
Duncan Sands1df98592010-02-16 11:11:14 +00003833 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003834 return Error(PtrLoc, "store operand must be a pointer");
3835 if (!Val->getType()->isFirstClassType())
3836 return Error(Loc, "store operand must be a first class value");
3837 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3838 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman21006d42011-08-09 23:02:53 +00003839 if (isAtomic && !Alignment)
3840 return Error(Loc, "atomic store must have explicit non-zero alignment");
3841 if (Ordering == Acquire || Ordering == AcquireRelease)
3842 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003843
Eli Friedman21006d42011-08-09 23:02:53 +00003844 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003845 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003846}
3847
Eli Friedmanff030482011-07-28 21:48:00 +00003848/// ParseCmpXchg
Eli Friedmanf03bb262011-08-12 22:50:01 +00003849/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3850/// 'singlethread'? AtomicOrdering
3851int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003852 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3853 bool AteExtraComma = false;
3854 AtomicOrdering Ordering = NotAtomic;
3855 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003856 bool isVolatile = false;
3857
3858 if (EatIfPresent(lltok::kw_volatile))
3859 isVolatile = true;
3860
Eli Friedmanff030482011-07-28 21:48:00 +00003861 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3862 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3863 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3864 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3865 ParseTypeAndValue(New, NewLoc, PFS) ||
3866 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3867 return true;
3868
3869 if (Ordering == Unordered)
3870 return TokError("cmpxchg cannot be unordered");
3871 if (!Ptr->getType()->isPointerTy())
3872 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3873 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3874 return Error(CmpLoc, "compare value and pointer type do not match");
3875 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3876 return Error(NewLoc, "new value and pointer type do not match");
3877 if (!New->getType()->isIntegerTy())
3878 return Error(NewLoc, "cmpxchg operand must be an integer");
3879 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3880 if (Size < 8 || (Size & (Size - 1)))
3881 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3882 " integer");
3883
3884 AtomicCmpXchgInst *CXI =
3885 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3886 CXI->setVolatile(isVolatile);
3887 Inst = CXI;
3888 return AteExtraComma ? InstExtraComma : InstNormal;
3889}
3890
3891/// ParseAtomicRMW
Eli Friedmanf03bb262011-08-12 22:50:01 +00003892/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3893/// 'singlethread'? AtomicOrdering
3894int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003895 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3896 bool AteExtraComma = false;
3897 AtomicOrdering Ordering = NotAtomic;
3898 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003899 bool isVolatile = false;
Eli Friedmanff030482011-07-28 21:48:00 +00003900 AtomicRMWInst::BinOp Operation;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003901
3902 if (EatIfPresent(lltok::kw_volatile))
3903 isVolatile = true;
3904
Eli Friedmanff030482011-07-28 21:48:00 +00003905 switch (Lex.getKind()) {
3906 default: return TokError("expected binary operation in atomicrmw");
3907 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3908 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3909 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3910 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3911 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3912 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3913 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3914 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3915 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3916 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3917 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3918 }
3919 Lex.Lex(); // Eat the operation.
3920
3921 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3922 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3923 ParseTypeAndValue(Val, ValLoc, PFS) ||
3924 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3925 return true;
3926
3927 if (Ordering == Unordered)
3928 return TokError("atomicrmw cannot be unordered");
3929 if (!Ptr->getType()->isPointerTy())
3930 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3931 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3932 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3933 if (!Val->getType()->isIntegerTy())
3934 return Error(ValLoc, "atomicrmw operand must be an integer");
3935 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3936 if (Size < 8 || (Size & (Size - 1)))
3937 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3938 " integer");
3939
3940 AtomicRMWInst *RMWI =
3941 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3942 RMWI->setVolatile(isVolatile);
3943 Inst = RMWI;
3944 return AteExtraComma ? InstExtraComma : InstNormal;
3945}
3946
Eli Friedman47f35132011-07-25 23:16:38 +00003947/// ParseFence
3948/// ::= 'fence' 'singlethread'? AtomicOrdering
3949int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3950 AtomicOrdering Ordering = NotAtomic;
3951 SynchronizationScope Scope = CrossThread;
3952 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3953 return true;
3954
3955 if (Ordering == Unordered)
3956 return TokError("fence cannot be unordered");
3957 if (Ordering == Monotonic)
3958 return TokError("fence cannot be monotonic");
3959
3960 Inst = new FenceInst(Context, Ordering, Scope);
3961 return InstNormal;
3962}
3963
Chris Lattnerdf986172009-01-02 07:01:27 +00003964/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003965/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003966int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Nadav Rotem16087692011-12-05 06:29:09 +00003967 Value *Ptr = 0;
3968 Value *Val = 0;
3969 LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003970
Dan Gohmandcb40a32009-07-29 15:58:36 +00003971 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003972
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003973 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003974
Nadav Rotem16087692011-12-05 06:29:09 +00003975 if (!Ptr->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003976 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003977
Chris Lattnerdf986172009-01-02 07:01:27 +00003978 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003979 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003980 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003981 if (Lex.getKind() == lltok::MetadataVar) {
3982 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003983 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003984 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003985 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem16087692011-12-05 06:29:09 +00003986 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003987 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem16087692011-12-05 06:29:09 +00003988 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
3989 return Error(EltLoc, "getelementptr index type missmatch");
3990 if (Val->getType()->isVectorTy()) {
3991 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
3992 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
3993 if (ValNumEl != PtrNumEl)
3994 return Error(EltLoc,
3995 "getelementptr vector index has a wrong number of elements");
3996 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003997 Indices.push_back(Val);
3998 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003999
Nadav Rotem16087692011-12-05 06:29:09 +00004000 if (Val && Val->getType()->isVectorTy() && Indices.size() != 1)
4001 return Error(EltLoc, "vector getelementptrs must have a single index");
4002
Jay Foada9203102011-07-25 09:48:08 +00004003 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004004 return Error(Loc, "invalid getelementptr indices");
Jay Foada9203102011-07-25 09:48:08 +00004005 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohmandd8004d2009-07-27 21:53:46 +00004006 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004007 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004008 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004009}
4010
4011/// ParseExtractValue
4012/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004013int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004014 Value *Val; LocTy Loc;
4015 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004016 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004017 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004018 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004019 return true;
4020
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004021 if (!Val->getType()->isAggregateType())
4022 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00004023
Jay Foadfc6d3a42011-07-13 10:26:04 +00004024 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004025 return Error(Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004026 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004027 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004028}
4029
4030/// ParseInsertValue
4031/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004032int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004033 Value *Val0, *Val1; LocTy Loc0, Loc1;
4034 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004035 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004036 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4037 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4038 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004039 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004040 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00004041
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004042 if (!Val0->getType()->isAggregateType())
4043 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004044
Jay Foadfc6d3a42011-07-13 10:26:04 +00004045 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004046 return Error(Loc0, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004047 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004048 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004049}
Nick Lewycky21cc4462009-04-04 07:22:01 +00004050
4051//===----------------------------------------------------------------------===//
4052// Embedded metadata.
4053//===----------------------------------------------------------------------===//
4054
4055/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00004056/// ::= Element (',' Element)*
4057/// Element
4058/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00004059bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00004060 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00004061 // Check for an empty list.
4062 if (Lex.getKind() == lltok::rbrace)
4063 return false;
4064
Nick Lewycky21cc4462009-04-04 07:22:01 +00004065 do {
Chris Lattnera7352392009-12-30 04:42:57 +00004066 // Null is a special case since it is typeless.
4067 if (EatIfPresent(lltok::kw_null)) {
4068 Elts.push_back(0);
4069 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00004070 }
Chris Lattnera7352392009-12-30 04:42:57 +00004071
4072 Value *V = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00004073 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00004074 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004075 } while (EatIfPresent(lltok::comma));
4076
4077 return false;
4078}