blob: de404728be6c73e0cf1480b2e5d4cce66803cc68 [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.
Bill Wendling702cc912012-10-15 20:35:56 +0000919bool LLParser::ParseOptionalAttrs(AttrBuilder &B, unsigned AttrKind) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000920 LocTy AttrLoc = Lex.getLoc();
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000921 bool HaveError = false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000922
Bill Wendlingf385f4c2012-10-08 23:27:46 +0000923 B.clear();
924
Chris Lattnerdf986172009-01-02 07:01:27 +0000925 while (1) {
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000926 lltok::Kind Token = Lex.getKind();
927 switch (Token) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000928 default: // End of attributes.
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000929 return HaveError;
Bill Wendling2e879bc2012-10-09 09:11:20 +0000930 case lltok::kw_zeroext: B.addAttribute(Attributes::ZExt); break;
931 case lltok::kw_signext: B.addAttribute(Attributes::SExt); break;
932 case lltok::kw_inreg: B.addAttribute(Attributes::InReg); break;
933 case lltok::kw_sret: B.addAttribute(Attributes::StructRet); break;
934 case lltok::kw_noalias: B.addAttribute(Attributes::NoAlias); break;
935 case lltok::kw_nocapture: B.addAttribute(Attributes::NoCapture); break;
936 case lltok::kw_byval: B.addAttribute(Attributes::ByVal); break;
937 case lltok::kw_nest: B.addAttribute(Attributes::Nest); break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000938
Bill Wendling2e879bc2012-10-09 09:11:20 +0000939 case lltok::kw_noreturn: B.addAttribute(Attributes::NoReturn); break;
940 case lltok::kw_nounwind: B.addAttribute(Attributes::NoUnwind); break;
941 case lltok::kw_uwtable: B.addAttribute(Attributes::UWTable); break;
942 case lltok::kw_returns_twice: B.addAttribute(Attributes::ReturnsTwice); break;
943 case lltok::kw_noinline: B.addAttribute(Attributes::NoInline); break;
944 case lltok::kw_readnone: B.addAttribute(Attributes::ReadNone); break;
945 case lltok::kw_readonly: B.addAttribute(Attributes::ReadOnly); break;
946 case lltok::kw_inlinehint: B.addAttribute(Attributes::InlineHint); break;
947 case lltok::kw_alwaysinline: B.addAttribute(Attributes::AlwaysInline); break;
948 case lltok::kw_optsize: B.addAttribute(Attributes::OptimizeForSize); break;
949 case lltok::kw_ssp: B.addAttribute(Attributes::StackProtect); break;
950 case lltok::kw_sspreq: B.addAttribute(Attributes::StackProtectReq); break;
951 case lltok::kw_noredzone: B.addAttribute(Attributes::NoRedZone); break;
952 case lltok::kw_noimplicitfloat: B.addAttribute(Attributes::NoImplicitFloat); break;
953 case lltok::kw_naked: B.addAttribute(Attributes::Naked); break;
954 case lltok::kw_nonlazybind: B.addAttribute(Attributes::NonLazyBind); break;
955 case lltok::kw_address_safety: B.addAttribute(Attributes::AddressSafety); break;
Quentin Colombet9a419f62012-10-30 16:32:52 +0000956 case lltok::kw_minsize: B.addAttribute(Attributes::MinSize); break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000957
Charles Davis1e063d12010-02-12 00:31:15 +0000958 case lltok::kw_alignstack: {
959 unsigned Alignment;
960 if (ParseOptionalStackAlignment(Alignment))
961 return true;
Bill Wendling03272442012-10-08 22:20:14 +0000962 B.addStackAlignmentAttr(Alignment);
Charles Davis1e063d12010-02-12 00:31:15 +0000963 continue;
964 }
965
Chris Lattnerdf986172009-01-02 07:01:27 +0000966 case lltok::kw_align: {
967 unsigned Alignment;
968 if (ParseOptionalAlignment(Alignment))
969 return true;
Bill Wendling03272442012-10-08 22:20:14 +0000970 B.addAlignmentAttr(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000971 continue;
972 }
Charles Davis1e063d12010-02-12 00:31:15 +0000973
Chris Lattnerdf986172009-01-02 07:01:27 +0000974 }
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000975
976 // Perform some error checking.
977 switch (Token) {
978 default:
979 if (AttrKind == 2)
980 HaveError |= Error(AttrLoc, "invalid use of attribute on a function");
981 break;
982 case lltok::kw_align:
983 // As a hack, we allow "align 2" on functions as a synonym for
984 // "alignstack 2".
985 break;
986
987 // Parameter Only:
988 case lltok::kw_sret:
989 case lltok::kw_nocapture:
990 case lltok::kw_byval:
991 case lltok::kw_nest:
992 if (AttrKind != 0)
993 HaveError |= Error(AttrLoc, "invalid use of parameter-only attribute");
994 break;
995
996 // Function Only:
997 case lltok::kw_noreturn:
998 case lltok::kw_nounwind:
999 case lltok::kw_readnone:
1000 case lltok::kw_readonly:
1001 case lltok::kw_noinline:
1002 case lltok::kw_alwaysinline:
1003 case lltok::kw_optsize:
1004 case lltok::kw_ssp:
1005 case lltok::kw_sspreq:
1006 case lltok::kw_noredzone:
1007 case lltok::kw_noimplicitfloat:
1008 case lltok::kw_naked:
1009 case lltok::kw_inlinehint:
1010 case lltok::kw_alignstack:
1011 case lltok::kw_uwtable:
1012 case lltok::kw_nonlazybind:
1013 case lltok::kw_returns_twice:
1014 case lltok::kw_address_safety:
Quentin Colombet9a419f62012-10-30 16:32:52 +00001015 case lltok::kw_minsize:
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001016 if (AttrKind != 2)
1017 HaveError |= Error(AttrLoc, "invalid use of function-only attribute");
1018 break;
1019 }
1020
Chris Lattnerdf986172009-01-02 07:01:27 +00001021 Lex.Lex();
1022 }
1023}
1024
1025/// ParseOptionalLinkage
1026/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001027/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001028/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001029/// ::= 'linker_private_weak'
Chris Lattnerdf986172009-01-02 07:01:27 +00001030/// ::= 'internal'
1031/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001032/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001033/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001034/// ::= 'linkonce_odr'
Bill Wendling32811be2012-08-17 18:33:14 +00001035/// ::= 'linkonce_odr_auto_hide'
Bill Wendling5e721d72010-07-01 21:55:59 +00001036/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001037/// ::= 'appending'
1038/// ::= 'dllexport'
1039/// ::= 'common'
1040/// ::= 'dllimport'
1041/// ::= 'extern_weak'
1042/// ::= 'external'
1043bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1044 HasLinkage = false;
1045 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001046 default: Res=GlobalValue::ExternalLinkage; return false;
1047 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1048 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001049 case lltok::kw_linker_private_weak:
1050 Res = GlobalValue::LinkerPrivateWeakLinkage;
1051 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001052 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1053 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1054 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1055 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1056 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Bill Wendling32811be2012-08-17 18:33:14 +00001057 case lltok::kw_linkonce_odr_auto_hide:
1058 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1059 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1060 break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001061 case lltok::kw_available_externally:
1062 Res = GlobalValue::AvailableExternallyLinkage;
1063 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001064 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1065 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1066 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1067 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1068 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1069 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001070 }
1071 Lex.Lex();
1072 HasLinkage = true;
1073 return false;
1074}
1075
1076/// ParseOptionalVisibility
1077/// ::= /*empty*/
1078/// ::= 'default'
1079/// ::= 'hidden'
1080/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001081///
Chris Lattnerdf986172009-01-02 07:01:27 +00001082bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1083 switch (Lex.getKind()) {
1084 default: Res = GlobalValue::DefaultVisibility; return false;
1085 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1086 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1087 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1088 }
1089 Lex.Lex();
1090 return false;
1091}
1092
1093/// ParseOptionalCallingConv
1094/// ::= /*empty*/
1095/// ::= 'ccc'
1096/// ::= 'fastcc'
Elena Demikhovsky35752222012-10-24 14:46:16 +00001097/// ::= 'kw_intel_ocl_bicc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001098/// ::= 'coldcc'
1099/// ::= 'x86_stdcallcc'
1100/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001101/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001102/// ::= 'arm_apcscc'
1103/// ::= 'arm_aapcscc'
1104/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001105/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001106/// ::= 'ptx_kernel'
1107/// ::= 'ptx_device'
Micah Villmowe53d6052012-10-01 17:01:31 +00001108/// ::= 'spir_func'
1109/// ::= 'spir_kernel'
Chris Lattnerdf986172009-01-02 07:01:27 +00001110/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001111///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001112bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001113 switch (Lex.getKind()) {
1114 default: CC = CallingConv::C; return false;
1115 case lltok::kw_ccc: CC = CallingConv::C; break;
1116 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1117 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1118 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1119 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001120 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001121 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1122 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1123 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001124 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001125 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1126 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmowe53d6052012-10-01 17:01:31 +00001127 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1128 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovsky35752222012-10-24 14:46:16 +00001129 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001130 case lltok::kw_cc: {
1131 unsigned ArbitraryCC;
1132 Lex.Lex();
David Blaikie4d6ccb52012-01-20 21:51:11 +00001133 if (ParseUInt32(ArbitraryCC))
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001134 return true;
David Blaikie4d6ccb52012-01-20 21:51:11 +00001135 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1136 return false;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001137 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001138 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001139
Chris Lattnerdf986172009-01-02 07:01:27 +00001140 Lex.Lex();
1141 return false;
1142}
1143
Chris Lattnerb8c46862009-12-30 05:31:19 +00001144/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001145/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001146bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1147 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001148 do {
1149 if (Lex.getKind() != lltok::MetadataVar)
1150 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001151
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001152 std::string Name = Lex.getStrVal();
Benjamin Kramer85dadec2011-12-06 11:50:26 +00001153 unsigned MDK = M->getMDKindID(Name);
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001154 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001155
Chris Lattner442ffa12009-12-29 21:53:55 +00001156 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001157 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001158
1159 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001160 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001161
Dan Gohman68261142010-08-24 14:35:45 +00001162 // This code is similar to that of ParseMetadataValue, however it needs to
1163 // have special-case code for a forward reference; see the comments on
1164 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1165 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001166 if (Lex.getKind() == lltok::lbrace) {
1167 ValID ID;
1168 if (ParseMetadataListValue(ID, PFS))
1169 return true;
1170 assert(ID.Kind == ValID::t_MDNode);
1171 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001172 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001173 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001174 if (ParseMDNodeID(Node, NodeID))
1175 return true;
1176 if (Node) {
1177 // If we got the node, add it to the instruction.
1178 Inst->setMetadata(MDK, Node);
1179 } else {
1180 MDRef R = { Loc, MDK, NodeID };
1181 // Otherwise, remember that this should be resolved later.
1182 ForwardRefInstMetadata[Inst].push_back(R);
1183 }
Chris Lattner449c3102010-04-01 05:14:45 +00001184 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001185
1186 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001187 } while (EatIfPresent(lltok::comma));
1188 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001189}
1190
Chris Lattnerdf986172009-01-02 07:01:27 +00001191/// ParseOptionalAlignment
1192/// ::= /* empty */
1193/// ::= 'align' 4
1194bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1195 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001196 if (!EatIfPresent(lltok::kw_align))
1197 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001198 LocTy AlignLoc = Lex.getLoc();
1199 if (ParseUInt32(Alignment)) return true;
1200 if (!isPowerOf2_32(Alignment))
1201 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001202 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001203 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001204 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001205}
1206
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001207/// ParseOptionalCommaAlign
1208/// ::=
1209/// ::= ',' align 4
1210///
1211/// This returns with AteExtraComma set to true if it ate an excess comma at the
1212/// end.
1213bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1214 bool &AteExtraComma) {
1215 AteExtraComma = false;
1216 while (EatIfPresent(lltok::comma)) {
1217 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001218 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001219 AteExtraComma = true;
1220 return false;
1221 }
1222
Chris Lattner093eed12010-04-23 00:50:50 +00001223 if (Lex.getKind() != lltok::kw_align)
1224 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001225
Chris Lattner093eed12010-04-23 00:50:50 +00001226 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001227 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001228
Devang Patelf633a062009-09-17 23:04:48 +00001229 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001230}
1231
Eli Friedman47f35132011-07-25 23:16:38 +00001232/// ParseScopeAndOrdering
1233/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1234/// else: ::=
1235///
1236/// This sets Scope and Ordering to the parsed values.
1237bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1238 AtomicOrdering &Ordering) {
1239 if (!isAtomic)
1240 return false;
1241
1242 Scope = CrossThread;
1243 if (EatIfPresent(lltok::kw_singlethread))
1244 Scope = SingleThread;
1245 switch (Lex.getKind()) {
1246 default: return TokError("Expected ordering on atomic instruction");
1247 case lltok::kw_unordered: Ordering = Unordered; break;
1248 case lltok::kw_monotonic: Ordering = Monotonic; break;
1249 case lltok::kw_acquire: Ordering = Acquire; break;
1250 case lltok::kw_release: Ordering = Release; break;
1251 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1252 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1253 }
1254 Lex.Lex();
1255 return false;
1256}
1257
Charles Davis1e063d12010-02-12 00:31:15 +00001258/// ParseOptionalStackAlignment
1259/// ::= /* empty */
1260/// ::= 'alignstack' '(' 4 ')'
1261bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1262 Alignment = 0;
1263 if (!EatIfPresent(lltok::kw_alignstack))
1264 return false;
1265 LocTy ParenLoc = Lex.getLoc();
1266 if (!EatIfPresent(lltok::lparen))
1267 return Error(ParenLoc, "expected '('");
1268 LocTy AlignLoc = Lex.getLoc();
1269 if (ParseUInt32(Alignment)) return true;
1270 ParenLoc = Lex.getLoc();
1271 if (!EatIfPresent(lltok::rparen))
1272 return Error(ParenLoc, "expected ')'");
1273 if (!isPowerOf2_32(Alignment))
1274 return Error(AlignLoc, "stack alignment is not a power of two");
1275 return false;
1276}
Devang Patelf633a062009-09-17 23:04:48 +00001277
Chris Lattner628c13a2009-12-30 05:14:00 +00001278/// ParseIndexList - This parses the index list for an insert/extractvalue
1279/// instruction. This sets AteExtraComma in the case where we eat an extra
1280/// comma at the end of the line and find that it is followed by metadata.
1281/// Clients that don't allow metadata can call the version of this function that
1282/// only takes one argument.
1283///
Chris Lattnerdf986172009-01-02 07:01:27 +00001284/// ParseIndexList
1285/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001286///
1287bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1288 bool &AteExtraComma) {
1289 AteExtraComma = false;
1290
Chris Lattnerdf986172009-01-02 07:01:27 +00001291 if (Lex.getKind() != lltok::comma)
1292 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001293
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001294 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001295 if (Lex.getKind() == lltok::MetadataVar) {
1296 AteExtraComma = true;
1297 return false;
1298 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001299 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001300 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001301 Indices.push_back(Idx);
1302 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001303
Chris Lattnerdf986172009-01-02 07:01:27 +00001304 return false;
1305}
1306
1307//===----------------------------------------------------------------------===//
1308// Type Parsing.
1309//===----------------------------------------------------------------------===//
1310
Chris Lattner1afcace2011-07-09 17:41:24 +00001311/// ParseType - Parse a type.
1312bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1313 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001314 switch (Lex.getKind()) {
1315 default:
1316 return TokError("expected type");
1317 case lltok::Type:
Chris Lattner1afcace2011-07-09 17:41:24 +00001318 // Type ::= 'float' | 'void' (etc)
Chris Lattnerdf986172009-01-02 07:01:27 +00001319 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001320 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001321 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001322 case lltok::lbrace:
Chris Lattner1afcace2011-07-09 17:41:24 +00001323 // Type ::= StructType
1324 if (ParseAnonStructType(Result, false))
Chris Lattnerdf986172009-01-02 07:01:27 +00001325 return true;
1326 break;
1327 case lltok::lsquare:
Chris Lattner1afcace2011-07-09 17:41:24 +00001328 // Type ::= '[' ... ']'
Chris Lattnerdf986172009-01-02 07:01:27 +00001329 Lex.Lex(); // eat the lsquare.
1330 if (ParseArrayVectorType(Result, false))
1331 return true;
1332 break;
1333 case lltok::less: // Either vector or packed struct.
Chris Lattner1afcace2011-07-09 17:41:24 +00001334 // Type ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001335 Lex.Lex();
1336 if (Lex.getKind() == lltok::lbrace) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001337 if (ParseAnonStructType(Result, true) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001338 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001339 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001340 } else if (ParseArrayVectorType(Result, true))
1341 return true;
1342 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001343 case lltok::LocalVar: {
1344 // Type ::= %foo
1345 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1346
1347 // If the type hasn't been defined yet, create a forward definition and
1348 // remember where that forward def'n was seen (in case it never is defined).
1349 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001350 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattner1afcace2011-07-09 17:41:24 +00001351 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001352 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001353 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001354 Lex.Lex();
1355 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001356 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001357
Chris Lattner1afcace2011-07-09 17:41:24 +00001358 case lltok::LocalVarID: {
1359 // Type ::= %4
1360 if (Lex.getUIntVal() >= NumberedTypes.size())
1361 NumberedTypes.resize(Lex.getUIntVal()+1);
1362 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1363
1364 // If the type hasn't been defined yet, create a forward definition and
1365 // remember where that forward def'n was seen (in case it never is defined).
1366 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001367 Entry.first = StructType::create(Context);
Chris Lattner1afcace2011-07-09 17:41:24 +00001368 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001369 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001370 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001371 Lex.Lex();
1372 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001373 }
1374 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001375
1376 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001377 while (1) {
1378 switch (Lex.getKind()) {
1379 // End of type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001380 default:
1381 if (!AllowVoid && Result->isVoidTy())
1382 return Error(TypeLoc, "void type only allowed for function results");
1383 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001384
Chris Lattner1afcace2011-07-09 17:41:24 +00001385 // Type ::= Type '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001386 case lltok::star:
Chris Lattner1afcace2011-07-09 17:41:24 +00001387 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001388 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001389 if (Result->isVoidTy())
1390 return TokError("pointers to void are invalid - use i8* instead");
1391 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001392 return TokError("pointer to this type is invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001393 Result = PointerType::getUnqual(Result);
Chris Lattnerdf986172009-01-02 07:01:27 +00001394 Lex.Lex();
1395 break;
1396
Chris Lattner1afcace2011-07-09 17:41:24 +00001397 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001398 case lltok::kw_addrspace: {
Chris Lattner1afcace2011-07-09 17:41:24 +00001399 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001400 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001401 if (Result->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001402 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattner1afcace2011-07-09 17:41:24 +00001403 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001404 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001405 unsigned AddrSpace;
1406 if (ParseOptionalAddrSpace(AddrSpace) ||
1407 ParseToken(lltok::star, "expected '*' in address space"))
1408 return true;
1409
Chris Lattner1afcace2011-07-09 17:41:24 +00001410 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001411 break;
1412 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001413
Chris Lattnerdf986172009-01-02 07:01:27 +00001414 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1415 case lltok::lparen:
1416 if (ParseFunctionType(Result))
1417 return true;
1418 break;
1419 }
1420 }
1421}
1422
1423/// ParseParameterList
1424/// ::= '(' ')'
1425/// ::= '(' Arg (',' Arg)* ')'
1426/// Arg
1427/// ::= Type OptionalAttributes Value OptionalAttributes
1428bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1429 PerFunctionState &PFS) {
1430 if (ParseToken(lltok::lparen, "expected '(' in call"))
1431 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001432
Chris Lattnerdf986172009-01-02 07:01:27 +00001433 while (Lex.getKind() != lltok::rparen) {
1434 // If this isn't the first argument, we need a comma.
1435 if (!ArgList.empty() &&
1436 ParseToken(lltok::comma, "expected ',' in argument list"))
1437 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001438
Chris Lattnerdf986172009-01-02 07:01:27 +00001439 // Parse the argument.
1440 LocTy ArgLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +00001441 Type *ArgTy = 0;
Bill Wendling702cc912012-10-15 20:35:56 +00001442 AttrBuilder ArgAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001443 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001444 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001445 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001446
Chris Lattner287881d2009-12-30 02:11:14 +00001447 // Otherwise, handle normal operands.
Bill Wendling03272442012-10-08 22:20:14 +00001448 if (ParseOptionalAttrs(ArgAttrs, 0) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001449 return true;
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001450 ArgList.push_back(ParamInfo(ArgLoc, V, Attributes::get(V->getContext(),
1451 ArgAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00001452 }
1453
1454 Lex.Lex(); // Lex the ')'.
1455 return false;
1456}
1457
1458
1459
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001460/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattner1afcace2011-07-09 17:41:24 +00001461/// prototype.
Chris Lattnerdf986172009-01-02 07:01:27 +00001462/// ::= '(' ArgTypeListI ')'
1463/// ArgTypeListI
1464/// ::= /*empty*/
1465/// ::= '...'
1466/// ::= ArgTypeList ',' '...'
1467/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001468///
Chris Lattner1afcace2011-07-09 17:41:24 +00001469bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1470 bool &isVarArg){
Chris Lattnerdf986172009-01-02 07:01:27 +00001471 isVarArg = false;
1472 assert(Lex.getKind() == lltok::lparen);
1473 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001474
Chris Lattnerdf986172009-01-02 07:01:27 +00001475 if (Lex.getKind() == lltok::rparen) {
1476 // empty
1477 } else if (Lex.getKind() == lltok::dotdotdot) {
1478 isVarArg = true;
1479 Lex.Lex();
1480 } else {
1481 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001482 Type *ArgTy = 0;
Bill Wendling702cc912012-10-15 20:35:56 +00001483 AttrBuilder Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001484 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001485
Chris Lattner1afcace2011-07-09 17:41:24 +00001486 if (ParseType(ArgTy) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001487 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001488
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001489 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001490 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001491
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001492 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001493 Name = Lex.getStrVal();
1494 Lex.Lex();
1495 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001496
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001497 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001498 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001499
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001500 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1501 Attributes::get(ArgTy->getContext(),
1502 Attrs), Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001503
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001504 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001505 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001506 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001507 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001508 break;
1509 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001510
Chris Lattnerdf986172009-01-02 07:01:27 +00001511 // Otherwise must be an argument type.
1512 TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001513 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001514
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001515 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001516 return Error(TypeLoc, "argument can not have void type");
1517
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001518 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001519 Name = Lex.getStrVal();
1520 Lex.Lex();
1521 } else {
1522 Name = "";
1523 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001524
Chris Lattner1afcace2011-07-09 17:41:24 +00001525 if (!ArgTy->isFirstClassType())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001526 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001527
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001528 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1529 Attributes::get(ArgTy->getContext(), Attrs),
1530 Name));
Chris Lattnerdf986172009-01-02 07:01:27 +00001531 }
1532 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001533
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001534 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001535}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001536
Chris Lattnerdf986172009-01-02 07:01:27 +00001537/// ParseFunctionType
1538/// ::= Type ArgumentList OptionalAttrs
Chris Lattner1afcace2011-07-09 17:41:24 +00001539bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001540 assert(Lex.getKind() == lltok::lparen);
1541
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001542 if (!FunctionType::isValidReturnType(Result))
1543 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001544
Chris Lattner1afcace2011-07-09 17:41:24 +00001545 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00001546 bool isVarArg;
Chris Lattner1afcace2011-07-09 17:41:24 +00001547 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerdf986172009-01-02 07:01:27 +00001548 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001549
Chris Lattnerdf986172009-01-02 07:01:27 +00001550 // Reject names on the arguments lists.
1551 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1552 if (!ArgList[i].Name.empty())
1553 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendling7be78482012-10-14 08:54:26 +00001554 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnera16546a2011-06-17 17:37:13 +00001555 return Error(ArgList[i].Loc,
1556 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001557 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001558
Jay Foad5fdd6c82011-07-12 14:06:48 +00001559 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerdf986172009-01-02 07:01:27 +00001560 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattner1afcace2011-07-09 17:41:24 +00001561 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001562
Chris Lattner1afcace2011-07-09 17:41:24 +00001563 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerdf986172009-01-02 07:01:27 +00001564 return false;
1565}
1566
Chris Lattner1afcace2011-07-09 17:41:24 +00001567/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1568/// other structs.
1569bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1570 SmallVector<Type*, 8> Elts;
1571 if (ParseStructBody(Elts)) return true;
1572
1573 Result = StructType::get(Context, Elts, Packed);
1574 return false;
1575}
1576
1577/// ParseStructDefinition - Parse a struct in a 'type' definition.
1578bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1579 std::pair<Type*, LocTy> &Entry,
1580 Type *&ResultTy) {
1581 // If the type was already defined, diagnose the redefinition.
1582 if (Entry.first && !Entry.second.isValid())
1583 return Error(TypeLoc, "redefinition of type");
1584
1585 // If we have opaque, just return without filling in the definition for the
1586 // struct. This counts as a definition as far as the .ll file goes.
1587 if (EatIfPresent(lltok::kw_opaque)) {
1588 // This type is being defined, so clear the location to indicate this.
1589 Entry.second = SMLoc();
1590
1591 // If this type number has never been uttered, create it.
1592 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001593 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001594 ResultTy = Entry.first;
1595 return false;
1596 }
1597
1598 // If the type starts with '<', then it is either a packed struct or a vector.
1599 bool isPacked = EatIfPresent(lltok::less);
1600
1601 // If we don't have a struct, then we have a random type alias, which we
1602 // accept for compatibility with old files. These types are not allowed to be
1603 // forward referenced and not allowed to be recursive.
1604 if (Lex.getKind() != lltok::lbrace) {
1605 if (Entry.first)
1606 return Error(TypeLoc, "forward references to non-struct type");
1607
1608 ResultTy = 0;
1609 if (isPacked)
1610 return ParseArrayVectorType(ResultTy, true);
1611 return ParseType(ResultTy);
1612 }
1613
1614 // This type is being defined, so clear the location to indicate this.
1615 Entry.second = SMLoc();
1616
1617 // If this type number has never been uttered, create it.
1618 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001619 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001620
1621 StructType *STy = cast<StructType>(Entry.first);
1622
1623 SmallVector<Type*, 8> Body;
1624 if (ParseStructBody(Body) ||
1625 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1626 return true;
1627
1628 STy->setBody(Body, isPacked);
1629 ResultTy = STy;
1630 return false;
1631}
1632
1633
Chris Lattnerdf986172009-01-02 07:01:27 +00001634/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattner1afcace2011-07-09 17:41:24 +00001635/// StructType
Chris Lattnerdf986172009-01-02 07:01:27 +00001636/// ::= '{' '}'
Chris Lattner1afcace2011-07-09 17:41:24 +00001637/// ::= '{' Type (',' Type)* '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00001638/// ::= '<' '{' '}' '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001639/// ::= '<' '{' Type (',' Type)* '}' '>'
1640bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001641 assert(Lex.getKind() == lltok::lbrace);
1642 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001643
Chris Lattner1afcace2011-07-09 17:41:24 +00001644 // Handle the empty struct.
1645 if (EatIfPresent(lltok::rbrace))
Chris Lattnerdf986172009-01-02 07:01:27 +00001646 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001647
Chris Lattnera9a9e072009-03-09 04:49:14 +00001648 LocTy EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001649 Type *Ty = 0;
1650 if (ParseType(Ty)) return true;
1651 Body.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001652
Chris Lattner1afcace2011-07-09 17:41:24 +00001653 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001654 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001655
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001656 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001657 EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001658 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001659
Chris Lattner1afcace2011-07-09 17:41:24 +00001660 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001661 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001662
Chris Lattner1afcace2011-07-09 17:41:24 +00001663 Body.push_back(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00001664 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001665
Chris Lattner1afcace2011-07-09 17:41:24 +00001666 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerdf986172009-01-02 07:01:27 +00001667}
1668
1669/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1670/// token has already been consumed.
Chris Lattner1afcace2011-07-09 17:41:24 +00001671/// Type
Chris Lattnerdf986172009-01-02 07:01:27 +00001672/// ::= '[' APSINTVAL 'x' Types ']'
1673/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001674bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001675 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1676 Lex.getAPSIntVal().getBitWidth() > 64)
1677 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001678
Chris Lattnerdf986172009-01-02 07:01:27 +00001679 LocTy SizeLoc = Lex.getLoc();
1680 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001681 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001682
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001683 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1684 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001685
1686 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001687 Type *EltTy = 0;
1688 if (ParseType(EltTy)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001689
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001690 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1691 "expected end of sequential type"))
1692 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001693
Chris Lattnerdf986172009-01-02 07:01:27 +00001694 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001695 if (Size == 0)
1696 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001697 if ((unsigned)Size != Size)
1698 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001699 if (!VectorType::isValidElementType(EltTy))
Duncan Sands2333e292012-11-13 12:59:33 +00001700 return Error(TypeLoc, "invalid vector element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001701 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001702 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001703 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001704 return Error(TypeLoc, "invalid array element type");
Chris Lattner1afcace2011-07-09 17:41:24 +00001705 Result = ArrayType::get(EltTy, Size);
Chris Lattnerdf986172009-01-02 07:01:27 +00001706 }
1707 return false;
1708}
1709
1710//===----------------------------------------------------------------------===//
1711// Function Semantic Analysis.
1712//===----------------------------------------------------------------------===//
1713
Chris Lattner09d9ef42009-10-28 03:39:23 +00001714LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1715 int functionNumber)
1716 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001717
1718 // Insert unnamed arguments into the NumberedVals list.
1719 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1720 AI != E; ++AI)
1721 if (!AI->hasName())
1722 NumberedVals.push_back(AI);
1723}
1724
1725LLParser::PerFunctionState::~PerFunctionState() {
1726 // If there were any forward referenced non-basicblock values, delete them.
1727 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1728 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1729 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001730 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001731 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001732 delete I->second.first;
1733 I->second.first = 0;
1734 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001735
Chris Lattnerdf986172009-01-02 07:01:27 +00001736 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1737 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1738 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001739 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001740 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001741 delete I->second.first;
1742 I->second.first = 0;
1743 }
1744}
1745
Chris Lattner09d9ef42009-10-28 03:39:23 +00001746bool LLParser::PerFunctionState::FinishFunction() {
1747 // Check to see if someone took the address of labels in this block.
1748 if (!P.ForwardRefBlockAddresses.empty()) {
1749 ValID FunctionID;
1750 if (!F.getName().empty()) {
1751 FunctionID.Kind = ValID::t_GlobalName;
1752 FunctionID.StrVal = F.getName();
1753 } else {
1754 FunctionID.Kind = ValID::t_GlobalID;
1755 FunctionID.UIntVal = FunctionNumber;
1756 }
1757
1758 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1759 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1760 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1761 // Resolve all these references.
1762 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1763 return true;
1764
1765 P.ForwardRefBlockAddresses.erase(FRBAI);
1766 }
1767 }
1768
Chris Lattnerdf986172009-01-02 07:01:27 +00001769 if (!ForwardRefVals.empty())
1770 return P.Error(ForwardRefVals.begin()->second.second,
1771 "use of undefined value '%" + ForwardRefVals.begin()->first +
1772 "'");
1773 if (!ForwardRefValIDs.empty())
1774 return P.Error(ForwardRefValIDs.begin()->second.second,
1775 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001776 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001777 return false;
1778}
1779
1780
1781/// GetVal - Get a value with the specified name or ID, creating a
1782/// forward reference record if needed. This can return null if the value
1783/// exists but does not have the right type.
1784Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001785 Type *Ty, LocTy Loc) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001786 // Look this name up in the normal function symbol table.
1787 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001788
Chris Lattnerdf986172009-01-02 07:01:27 +00001789 // If this is a forward reference for the value, see if we already created a
1790 // forward ref record.
1791 if (Val == 0) {
1792 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1793 I = ForwardRefVals.find(Name);
1794 if (I != ForwardRefVals.end())
1795 Val = I->second.first;
1796 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001797
Chris Lattnerdf986172009-01-02 07:01:27 +00001798 // If we have the value in the symbol table or fwd-ref table, return it.
1799 if (Val) {
1800 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001801 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001802 P.Error(Loc, "'%" + Name + "' is not a basic block");
1803 else
1804 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001805 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001806 return 0;
1807 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001808
Chris Lattnerdf986172009-01-02 07:01:27 +00001809 // Don't make placeholders with invalid type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001810 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001811 P.Error(Loc, "invalid use of a non-first-class type");
1812 return 0;
1813 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001814
Chris Lattnerdf986172009-01-02 07:01:27 +00001815 // Otherwise, create a new forward reference for this value and remember it.
1816 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001817 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001818 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001819 else
1820 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001821
Chris Lattnerdf986172009-01-02 07:01:27 +00001822 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1823 return FwdVal;
1824}
1825
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001826Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +00001827 LocTy Loc) {
1828 // Look this name up in the normal function symbol table.
1829 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001830
Chris Lattnerdf986172009-01-02 07:01:27 +00001831 // If this is a forward reference for the value, see if we already created a
1832 // forward ref record.
1833 if (Val == 0) {
1834 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1835 I = ForwardRefValIDs.find(ID);
1836 if (I != ForwardRefValIDs.end())
1837 Val = I->second.first;
1838 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001839
Chris Lattnerdf986172009-01-02 07:01:27 +00001840 // If we have the value in the symbol table or fwd-ref table, return it.
1841 if (Val) {
1842 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001843 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001844 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001845 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001846 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001847 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001848 return 0;
1849 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001850
Chris Lattner1afcace2011-07-09 17:41:24 +00001851 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001852 P.Error(Loc, "invalid use of a non-first-class type");
1853 return 0;
1854 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001855
Chris Lattnerdf986172009-01-02 07:01:27 +00001856 // Otherwise, create a new forward reference for this value and remember it.
1857 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001858 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001859 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001860 else
1861 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001862
Chris Lattnerdf986172009-01-02 07:01:27 +00001863 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1864 return FwdVal;
1865}
1866
1867/// SetInstName - After an instruction is parsed and inserted into its
1868/// basic block, this installs its name.
1869bool LLParser::PerFunctionState::SetInstName(int NameID,
1870 const std::string &NameStr,
1871 LocTy NameLoc, Instruction *Inst) {
1872 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001873 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001874 if (NameID != -1 || !NameStr.empty())
1875 return P.Error(NameLoc, "instructions returning void cannot have a name");
1876 return false;
1877 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001878
Chris Lattnerdf986172009-01-02 07:01:27 +00001879 // If this was a numbered instruction, verify that the instruction is the
1880 // expected value and resolve any forward references.
1881 if (NameStr.empty()) {
1882 // If neither a name nor an ID was specified, just use the next ID.
1883 if (NameID == -1)
1884 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001885
Chris Lattnerdf986172009-01-02 07:01:27 +00001886 if (unsigned(NameID) != NumberedVals.size())
1887 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001888 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001889
Chris Lattnerdf986172009-01-02 07:01:27 +00001890 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1891 ForwardRefValIDs.find(NameID);
1892 if (FI != ForwardRefValIDs.end()) {
1893 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001894 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001895 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001896 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001897 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001898 ForwardRefValIDs.erase(FI);
1899 }
1900
1901 NumberedVals.push_back(Inst);
1902 return false;
1903 }
1904
1905 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1906 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1907 FI = ForwardRefVals.find(NameStr);
1908 if (FI != ForwardRefVals.end()) {
1909 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001910 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001911 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001912 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001913 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001914 ForwardRefVals.erase(FI);
1915 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001916
Chris Lattnerdf986172009-01-02 07:01:27 +00001917 // Set the name on the instruction.
1918 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001919
Benjamin Krameraf812352010-10-16 11:28:23 +00001920 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001921 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001922 NameStr + "'");
1923 return false;
1924}
1925
1926/// GetBB - Get a basic block with the specified name or ID, creating a
1927/// forward reference record if needed.
1928BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1929 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001930 return cast_or_null<BasicBlock>(GetVal(Name,
1931 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001932}
1933
1934BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001935 return cast_or_null<BasicBlock>(GetVal(ID,
1936 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001937}
1938
1939/// DefineBB - Define the specified basic block, which is either named or
1940/// unnamed. If there is an error, this returns null otherwise it returns
1941/// the block being defined.
1942BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1943 LocTy Loc) {
1944 BasicBlock *BB;
1945 if (Name.empty())
1946 BB = GetBB(NumberedVals.size(), Loc);
1947 else
1948 BB = GetBB(Name, Loc);
1949 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001950
Chris Lattnerdf986172009-01-02 07:01:27 +00001951 // Move the block to the end of the function. Forward ref'd blocks are
1952 // inserted wherever they happen to be referenced.
1953 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001954
Chris Lattnerdf986172009-01-02 07:01:27 +00001955 // Remove the block from forward ref sets.
1956 if (Name.empty()) {
1957 ForwardRefValIDs.erase(NumberedVals.size());
1958 NumberedVals.push_back(BB);
1959 } else {
1960 // BB forward references are already in the function symbol table.
1961 ForwardRefVals.erase(Name);
1962 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001963
Chris Lattnerdf986172009-01-02 07:01:27 +00001964 return BB;
1965}
1966
1967//===----------------------------------------------------------------------===//
1968// Constants.
1969//===----------------------------------------------------------------------===//
1970
1971/// ParseValID - Parse an abstract value that doesn't necessarily have a
1972/// type implied. For example, if we parse "4" we don't know what integer type
1973/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001974/// sanity. PFS is used to convert function-local operands of metadata (since
1975/// metadata operands are not just parsed here but also converted to values).
1976/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001977bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001978 ID.Loc = Lex.getLoc();
1979 switch (Lex.getKind()) {
1980 default: return TokError("expected value token");
1981 case lltok::GlobalID: // @42
1982 ID.UIntVal = Lex.getUIntVal();
1983 ID.Kind = ValID::t_GlobalID;
1984 break;
1985 case lltok::GlobalVar: // @foo
1986 ID.StrVal = Lex.getStrVal();
1987 ID.Kind = ValID::t_GlobalName;
1988 break;
1989 case lltok::LocalVarID: // %42
1990 ID.UIntVal = Lex.getUIntVal();
1991 ID.Kind = ValID::t_LocalID;
1992 break;
1993 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00001994 ID.StrVal = Lex.getStrVal();
1995 ID.Kind = ValID::t_LocalName;
1996 break;
Dan Gohman83448032010-07-14 18:26:50 +00001997 case lltok::exclaim: // !42, !{...}, or !"foo"
1998 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00001999 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002000 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002001 ID.Kind = ValID::t_APSInt;
2002 break;
2003 case lltok::APFloat:
2004 ID.APFloatVal = Lex.getAPFloatVal();
2005 ID.Kind = ValID::t_APFloat;
2006 break;
2007 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002008 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002009 ID.Kind = ValID::t_Constant;
2010 break;
2011 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002012 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002013 ID.Kind = ValID::t_Constant;
2014 break;
2015 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2016 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2017 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002018
Chris Lattnerdf986172009-01-02 07:01:27 +00002019 case lltok::lbrace: {
2020 // ValID ::= '{' ConstVector '}'
2021 Lex.Lex();
2022 SmallVector<Constant*, 16> Elts;
2023 if (ParseGlobalValueVector(Elts) ||
2024 ParseToken(lltok::rbrace, "expected end of struct constant"))
2025 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002026
Chris Lattner1afcace2011-07-09 17:41:24 +00002027 ID.ConstantStructElts = new Constant*[Elts.size()];
2028 ID.UIntVal = Elts.size();
2029 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2030 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002031 return false;
2032 }
2033 case lltok::less: {
2034 // ValID ::= '<' ConstVector '>' --> Vector.
2035 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2036 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002037 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002038
Chris Lattnerdf986172009-01-02 07:01:27 +00002039 SmallVector<Constant*, 16> Elts;
2040 LocTy FirstEltLoc = Lex.getLoc();
2041 if (ParseGlobalValueVector(Elts) ||
2042 (isPackedStruct &&
2043 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2044 ParseToken(lltok::greater, "expected end of constant"))
2045 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002046
Chris Lattnerdf986172009-01-02 07:01:27 +00002047 if (isPackedStruct) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002048 ID.ConstantStructElts = new Constant*[Elts.size()];
2049 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2050 ID.UIntVal = Elts.size();
2051 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002052 return false;
2053 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002054
Chris Lattnerdf986172009-01-02 07:01:27 +00002055 if (Elts.empty())
2056 return Error(ID.Loc, "constant vector must not be empty");
2057
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002058 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002059 !Elts[0]->getType()->isFloatingPointTy() &&
2060 !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002061 return Error(FirstEltLoc,
Nadav Rotem16087692011-12-05 06:29:09 +00002062 "vector elements must have integer, pointer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002063
Chris Lattnerdf986172009-01-02 07:01:27 +00002064 // Verify that all the vector elements have the same type.
2065 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2066 if (Elts[i]->getType() != Elts[0]->getType())
2067 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002068 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002069 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002070
Chris Lattner2ca5c862011-02-15 00:14:00 +00002071 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002072 ID.Kind = ValID::t_Constant;
2073 return false;
2074 }
2075 case lltok::lsquare: { // Array Constant
2076 Lex.Lex();
2077 SmallVector<Constant*, 16> Elts;
2078 LocTy FirstEltLoc = Lex.getLoc();
2079 if (ParseGlobalValueVector(Elts) ||
2080 ParseToken(lltok::rsquare, "expected end of array constant"))
2081 return true;
2082
2083 // Handle empty element.
2084 if (Elts.empty()) {
2085 // Use undef instead of an array because it's inconvenient to determine
2086 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002087 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002088 return false;
2089 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002090
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002092 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002093 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002094
Owen Andersondebcb012009-07-29 22:17:13 +00002095 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002096
Chris Lattnerdf986172009-01-02 07:01:27 +00002097 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002098 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002099 if (Elts[i]->getType() != Elts[0]->getType())
2100 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002101 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002102 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00002103 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002104
Jay Foad26701082011-06-22 09:24:39 +00002105 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002106 ID.Kind = ValID::t_Constant;
2107 return false;
2108 }
2109 case lltok::kw_c: // c "foo"
2110 Lex.Lex();
Chris Lattner18c7f802012-02-05 02:29:43 +00002111 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2112 false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002113 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2114 ID.Kind = ValID::t_Constant;
2115 return false;
2116
2117 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002118 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
Chad Rosier581600b2012-09-05 19:00:49 +00002119 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerdf986172009-01-02 07:01:27 +00002120 Lex.Lex();
2121 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002122 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosier581600b2012-09-05 19:00:49 +00002123 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002124 ParseStringConstant(ID.StrVal) ||
2125 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002126 ParseToken(lltok::StringConstant, "expected constraint string"))
2127 return true;
2128 ID.StrVal2 = Lex.getStrVal();
Chad Rosier36547342012-09-05 00:08:17 +00002129 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosier581600b2012-09-05 19:00:49 +00002130 (unsigned(AsmDialect)<<2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002131 ID.Kind = ValID::t_InlineAsm;
2132 return false;
2133 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002134
Chris Lattner09d9ef42009-10-28 03:39:23 +00002135 case lltok::kw_blockaddress: {
2136 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2137 Lex.Lex();
2138
2139 ValID Fn, Label;
2140 LocTy FnLoc, LabelLoc;
2141
2142 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2143 ParseValID(Fn) ||
2144 ParseToken(lltok::comma, "expected comma in block address expression")||
2145 ParseValID(Label) ||
2146 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2147 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002148
Chris Lattner09d9ef42009-10-28 03:39:23 +00002149 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2150 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002151 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002152 return Error(Label.Loc, "expected basic block name in blockaddress");
2153
2154 // Make a global variable as a placeholder for this reference.
2155 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2156 false, GlobalValue::InternalLinkage,
2157 0, "");
2158 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2159 ID.ConstantVal = FwdRef;
2160 ID.Kind = ValID::t_Constant;
2161 return false;
2162 }
2163
Chris Lattnerdf986172009-01-02 07:01:27 +00002164 case lltok::kw_trunc:
2165 case lltok::kw_zext:
2166 case lltok::kw_sext:
2167 case lltok::kw_fptrunc:
2168 case lltok::kw_fpext:
2169 case lltok::kw_bitcast:
2170 case lltok::kw_uitofp:
2171 case lltok::kw_sitofp:
2172 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002173 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002174 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002175 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002176 unsigned Opc = Lex.getUIntVal();
Chris Lattner1afcace2011-07-09 17:41:24 +00002177 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002178 Constant *SrcVal;
2179 Lex.Lex();
2180 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2181 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002182 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002183 ParseType(DestTy) ||
2184 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2185 return true;
2186 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2187 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002188 getTypeString(SrcVal->getType()) + "' to '" +
2189 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002190 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002191 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002192 ID.Kind = ValID::t_Constant;
2193 return false;
2194 }
2195 case lltok::kw_extractvalue: {
2196 Lex.Lex();
2197 Constant *Val;
2198 SmallVector<unsigned, 4> Indices;
2199 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2200 ParseGlobalTypeAndValue(Val) ||
2201 ParseIndexList(Indices) ||
2202 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2203 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002204
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002205 if (!Val->getType()->isAggregateType())
2206 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002207 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002208 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002209 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002210 ID.Kind = ValID::t_Constant;
2211 return false;
2212 }
2213 case lltok::kw_insertvalue: {
2214 Lex.Lex();
2215 Constant *Val0, *Val1;
2216 SmallVector<unsigned, 4> Indices;
2217 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2218 ParseGlobalTypeAndValue(Val0) ||
2219 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2220 ParseGlobalTypeAndValue(Val1) ||
2221 ParseIndexList(Indices) ||
2222 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2223 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002224 if (!Val0->getType()->isAggregateType())
2225 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002226 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002227 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002228 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002229 ID.Kind = ValID::t_Constant;
2230 return false;
2231 }
2232 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002233 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002234 unsigned PredVal, Opc = Lex.getUIntVal();
2235 Constant *Val0, *Val1;
2236 Lex.Lex();
2237 if (ParseCmpPredicate(PredVal, Opc) ||
2238 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2239 ParseGlobalTypeAndValue(Val0) ||
2240 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2241 ParseGlobalTypeAndValue(Val1) ||
2242 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2243 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002244
Chris Lattnerdf986172009-01-02 07:01:27 +00002245 if (Val0->getType() != Val1->getType())
2246 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002247
Chris Lattnerdf986172009-01-02 07:01:27 +00002248 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002249
Chris Lattnerdf986172009-01-02 07:01:27 +00002250 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002251 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002252 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002253 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002254 } else {
2255 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002256 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002257 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002258 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002259 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002260 }
2261 ID.Kind = ValID::t_Constant;
2262 return false;
2263 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002264
Chris Lattnerdf986172009-01-02 07:01:27 +00002265 // Binary Operators.
2266 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002267 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002268 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002269 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002270 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002271 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002272 case lltok::kw_udiv:
2273 case lltok::kw_sdiv:
2274 case lltok::kw_fdiv:
2275 case lltok::kw_urem:
2276 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002277 case lltok::kw_frem:
2278 case lltok::kw_shl:
2279 case lltok::kw_lshr:
2280 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002281 bool NUW = false;
2282 bool NSW = false;
2283 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002284 unsigned Opc = Lex.getUIntVal();
2285 Constant *Val0, *Val1;
2286 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002287 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002288 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2289 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002290 if (EatIfPresent(lltok::kw_nuw))
2291 NUW = true;
2292 if (EatIfPresent(lltok::kw_nsw)) {
2293 NSW = true;
2294 if (EatIfPresent(lltok::kw_nuw))
2295 NUW = true;
2296 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002297 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2298 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002299 if (EatIfPresent(lltok::kw_exact))
2300 Exact = true;
2301 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002302 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2303 ParseGlobalTypeAndValue(Val0) ||
2304 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2305 ParseGlobalTypeAndValue(Val1) ||
2306 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2307 return true;
2308 if (Val0->getType() != Val1->getType())
2309 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002310 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002311 if (NUW)
2312 return Error(ModifierLoc, "nuw only applies to integer operations");
2313 if (NSW)
2314 return Error(ModifierLoc, "nsw only applies to integer operations");
2315 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002316 // Check that the type is valid for the operator.
2317 switch (Opc) {
2318 case Instruction::Add:
2319 case Instruction::Sub:
2320 case Instruction::Mul:
2321 case Instruction::UDiv:
2322 case Instruction::SDiv:
2323 case Instruction::URem:
2324 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002325 case Instruction::Shl:
2326 case Instruction::AShr:
2327 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002328 if (!Val0->getType()->isIntOrIntVectorTy())
2329 return Error(ID.Loc, "constexpr requires integer operands");
2330 break;
2331 case Instruction::FAdd:
2332 case Instruction::FSub:
2333 case Instruction::FMul:
2334 case Instruction::FDiv:
2335 case Instruction::FRem:
2336 if (!Val0->getType()->isFPOrFPVectorTy())
2337 return Error(ID.Loc, "constexpr requires fp operands");
2338 break;
2339 default: llvm_unreachable("Unknown binary operator!");
2340 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002341 unsigned Flags = 0;
2342 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2343 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002344 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002345 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002346 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002347 ID.Kind = ValID::t_Constant;
2348 return false;
2349 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002350
Chris Lattnerdf986172009-01-02 07:01:27 +00002351 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002352 case lltok::kw_and:
2353 case lltok::kw_or:
2354 case lltok::kw_xor: {
2355 unsigned Opc = Lex.getUIntVal();
2356 Constant *Val0, *Val1;
2357 Lex.Lex();
2358 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2359 ParseGlobalTypeAndValue(Val0) ||
2360 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2361 ParseGlobalTypeAndValue(Val1) ||
2362 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2363 return true;
2364 if (Val0->getType() != Val1->getType())
2365 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002366 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002367 return Error(ID.Loc,
2368 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002369 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002370 ID.Kind = ValID::t_Constant;
2371 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002372 }
2373
Chris Lattnerdf986172009-01-02 07:01:27 +00002374 case lltok::kw_getelementptr:
2375 case lltok::kw_shufflevector:
2376 case lltok::kw_insertelement:
2377 case lltok::kw_extractelement:
2378 case lltok::kw_select: {
2379 unsigned Opc = Lex.getUIntVal();
2380 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002381 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002382 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002383 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002384 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002385 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2386 ParseGlobalValueVector(Elts) ||
2387 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2388 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002389
Chris Lattnerdf986172009-01-02 07:01:27 +00002390 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem16087692011-12-05 06:29:09 +00002391 if (Elts.size() == 0 ||
2392 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002393 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002394
Jay Foaddab3d292011-07-21 14:31:17 +00002395 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foada9203102011-07-25 09:48:08 +00002396 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002397 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad4b5e2072011-07-21 15:15:37 +00002398 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2399 InBounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002400 } else if (Opc == Instruction::Select) {
2401 if (Elts.size() != 3)
2402 return Error(ID.Loc, "expected three operands to select");
2403 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2404 Elts[2]))
2405 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002406 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002407 } else if (Opc == Instruction::ShuffleVector) {
2408 if (Elts.size() != 3)
2409 return Error(ID.Loc, "expected three operands to shufflevector");
2410 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2411 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002412 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002413 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002414 } else if (Opc == Instruction::ExtractElement) {
2415 if (Elts.size() != 2)
2416 return Error(ID.Loc, "expected two operands to extractelement");
2417 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2418 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002419 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002420 } else {
2421 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2422 if (Elts.size() != 3)
2423 return Error(ID.Loc, "expected three operands to insertelement");
2424 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2425 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002426 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002427 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002428 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002429
Chris Lattnerdf986172009-01-02 07:01:27 +00002430 ID.Kind = ValID::t_Constant;
2431 return false;
2432 }
2433 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002434
Chris Lattnerdf986172009-01-02 07:01:27 +00002435 Lex.Lex();
2436 return false;
2437}
2438
2439/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002440bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez92f238d2010-01-11 22:31:58 +00002441 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002442 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002443 Value *V = NULL;
2444 bool Parsed = ParseValID(ID) ||
2445 ConvertValIDToValue(Ty, ID, V, NULL);
2446 if (V && !(C = dyn_cast<Constant>(V)))
2447 return Error(ID.Loc, "global values must be constants");
2448 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002449}
2450
Victor Hernandez92f238d2010-01-11 22:31:58 +00002451bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002452 Type *Ty = 0;
2453 return ParseType(Ty) ||
2454 ParseGlobalValue(Ty, V);
Victor Hernandez92f238d2010-01-11 22:31:58 +00002455}
2456
2457/// ParseGlobalValueVector
2458/// ::= /*empty*/
2459/// ::= TypeAndValue (',' TypeAndValue)*
2460bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2461 // Empty list.
2462 if (Lex.getKind() == lltok::rbrace ||
2463 Lex.getKind() == lltok::rsquare ||
2464 Lex.getKind() == lltok::greater ||
2465 Lex.getKind() == lltok::rparen)
2466 return false;
2467
2468 Constant *C;
2469 if (ParseGlobalTypeAndValue(C)) return true;
2470 Elts.push_back(C);
2471
2472 while (EatIfPresent(lltok::comma)) {
2473 if (ParseGlobalTypeAndValue(C)) return true;
2474 Elts.push_back(C);
2475 }
2476
2477 return false;
2478}
2479
Dan Gohman309b3af2010-08-24 02:24:03 +00002480bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2481 assert(Lex.getKind() == lltok::lbrace);
2482 Lex.Lex();
2483
2484 SmallVector<Value*, 16> Elts;
2485 if (ParseMDNodeVector(Elts, PFS) ||
2486 ParseToken(lltok::rbrace, "expected end of metadata node"))
2487 return true;
2488
Jay Foadec9186b2011-04-21 19:59:31 +00002489 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002490 ID.Kind = ValID::t_MDNode;
2491 return false;
2492}
2493
Dan Gohman83448032010-07-14 18:26:50 +00002494/// ParseMetadataValue
2495/// ::= !42
2496/// ::= !{...}
2497/// ::= !"string"
2498bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2499 assert(Lex.getKind() == lltok::exclaim);
2500 Lex.Lex();
2501
2502 // MDNode:
2503 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002504 if (Lex.getKind() == lltok::lbrace)
2505 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002506
2507 // Standalone metadata reference
2508 // !42
2509 if (Lex.getKind() == lltok::APSInt) {
2510 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2511 ID.Kind = ValID::t_MDNode;
2512 return false;
2513 }
2514
2515 // MDString:
2516 // ::= '!' STRINGCONSTANT
2517 if (ParseMDString(ID.MDStringVal)) return true;
2518 ID.Kind = ValID::t_MDString;
2519 return false;
2520}
2521
Victor Hernandez92f238d2010-01-11 22:31:58 +00002522
2523//===----------------------------------------------------------------------===//
2524// Function Parsing.
2525//===----------------------------------------------------------------------===//
2526
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002527bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez92f238d2010-01-11 22:31:58 +00002528 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002529 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002530 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002531
Chris Lattnerdf986172009-01-02 07:01:27 +00002532 switch (ID.Kind) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002533 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002534 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2535 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2536 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002537 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002538 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2539 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2540 return (V == 0);
2541 case ValID::t_InlineAsm: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002542 PointerType *PTy = dyn_cast<PointerType>(Ty);
2543 FunctionType *FTy =
Victor Hernandez92f238d2010-01-11 22:31:58 +00002544 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2545 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2546 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosier36547342012-09-05 00:08:17 +00002547 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosier581600b2012-09-05 19:00:49 +00002548 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez92f238d2010-01-11 22:31:58 +00002549 return false;
2550 }
2551 case ValID::t_MDNode:
2552 if (!Ty->isMetadataTy())
2553 return Error(ID.Loc, "metadata value must have metadata type");
2554 V = ID.MDNodeVal;
2555 return false;
2556 case ValID::t_MDString:
2557 if (!Ty->isMetadataTy())
2558 return Error(ID.Loc, "metadata value must have metadata type");
2559 V = ID.MDStringVal;
2560 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002561 case ValID::t_GlobalName:
2562 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2563 return V == 0;
2564 case ValID::t_GlobalID:
2565 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2566 return V == 0;
2567 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002568 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002569 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002570 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002571 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002572 return false;
2573 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002574 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002575 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2576 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002577
Dan Gohmance163392011-12-17 00:04:22 +00002578 // The lexer has no type info, so builds all half, float, and double FP
2579 // constants as double. Fix this here. Long double does not need this.
2580 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002581 bool Ignored;
Dan Gohmance163392011-12-17 00:04:22 +00002582 if (Ty->isHalfTy())
2583 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2584 &Ignored);
2585 else if (Ty->isFloatTy())
2586 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2587 &Ignored);
Chris Lattnerdf986172009-01-02 07:01:27 +00002588 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002589 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002590
Chris Lattner959873d2009-01-05 18:24:23 +00002591 if (V->getType() != Ty)
2592 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002593 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002594
Chris Lattnerdf986172009-01-02 07:01:27 +00002595 return false;
2596 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002597 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002598 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002599 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002600 return false;
2601 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002602 // FIXME: LabelTy should not be a first-class type.
Chris Lattner1afcace2011-07-09 17:41:24 +00002603 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002604 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002605 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002606 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002607 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002608 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002609 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002610 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002611 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002612 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002613 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002614 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002615 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002616 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002617 return false;
2618 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002619 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002620 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002621
Chris Lattnerdf986172009-01-02 07:01:27 +00002622 V = ID.ConstantVal;
2623 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +00002624 case ValID::t_ConstantStruct:
2625 case ValID::t_PackedConstantStruct:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002626 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002627 if (ST->getNumElements() != ID.UIntVal)
2628 return Error(ID.Loc,
2629 "initializer with struct type has wrong # elements");
2630 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2631 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2632
2633 // Verify that the elements are compatible with the structtype.
2634 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2635 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2636 return Error(ID.Loc, "element " + Twine(i) +
2637 " of struct initializer doesn't match struct element type");
2638
Frits van Bommel39b5abf2011-07-18 12:00:32 +00002639 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2640 ID.UIntVal));
Chris Lattner1afcace2011-07-09 17:41:24 +00002641 } else
2642 return Error(ID.Loc, "constant expression type mismatch");
2643 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002644 }
Chandler Carruth732f05c2012-01-10 18:08:01 +00002645 llvm_unreachable("Invalid ValID");
Chris Lattnerdf986172009-01-02 07:01:27 +00002646}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002647
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002648bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002649 V = 0;
2650 ValID ID;
Chris Lattner1afcace2011-07-09 17:41:24 +00002651 return ParseValID(ID, PFS) ||
2652 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002653}
2654
Chris Lattner1afcace2011-07-09 17:41:24 +00002655bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2656 Type *Ty = 0;
2657 return ParseType(Ty) ||
2658 ParseValue(Ty, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002659}
2660
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002661bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2662 PerFunctionState &PFS) {
2663 Value *V;
2664 Loc = Lex.getLoc();
2665 if (ParseTypeAndValue(V, PFS)) return true;
2666 if (!isa<BasicBlock>(V))
2667 return Error(Loc, "expected a basic block");
2668 BB = cast<BasicBlock>(V);
2669 return false;
2670}
2671
2672
Chris Lattnerdf986172009-01-02 07:01:27 +00002673/// FunctionHeader
2674/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002675/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002676/// OptionalAlign OptGC
2677bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2678 // Parse the linkage.
2679 LocTy LinkageLoc = Lex.getLoc();
2680 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002681
Kostya Serebryany164b86b2012-01-20 17:56:17 +00002682 unsigned Visibility;
Bill Wendling702cc912012-10-15 20:35:56 +00002683 AttrBuilder RetAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002684 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00002685 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002686 LocTy RetTypeLoc = Lex.getLoc();
2687 if (ParseOptionalLinkage(Linkage) ||
2688 ParseOptionalVisibility(Visibility) ||
2689 ParseOptionalCallingConv(CC) ||
2690 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002691 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002692 return true;
2693
2694 // Verify that the linkage is ok.
2695 switch ((GlobalValue::LinkageTypes)Linkage) {
2696 case GlobalValue::ExternalLinkage:
2697 break; // always ok.
2698 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002699 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002700 if (isDefine)
2701 return Error(LinkageLoc, "invalid linkage for function definition");
2702 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002703 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002704 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002705 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002706 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002707 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002708 case GlobalValue::LinkOnceAnyLinkage:
2709 case GlobalValue::LinkOnceODRLinkage:
Bill Wendling32811be2012-08-17 18:33:14 +00002710 case GlobalValue::LinkOnceODRAutoHideLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002711 case GlobalValue::WeakAnyLinkage:
2712 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002713 case GlobalValue::DLLExportLinkage:
2714 if (!isDefine)
2715 return Error(LinkageLoc, "invalid linkage for function declaration");
2716 break;
2717 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002718 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002719 return Error(LinkageLoc, "invalid function linkage type");
2720 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002721
Chris Lattner1afcace2011-07-09 17:41:24 +00002722 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002723 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002724
Chris Lattnerdf986172009-01-02 07:01:27 +00002725 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002726
2727 std::string FunctionName;
2728 if (Lex.getKind() == lltok::GlobalVar) {
2729 FunctionName = Lex.getStrVal();
2730 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2731 unsigned NameID = Lex.getUIntVal();
2732
2733 if (NameID != NumberedVals.size())
2734 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002735 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002736 } else {
2737 return TokError("expected function name");
2738 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002739
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002740 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002741
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002742 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002743 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002744
Chris Lattner1afcace2011-07-09 17:41:24 +00002745 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002746 bool isVarArg;
Bill Wendling702cc912012-10-15 20:35:56 +00002747 AttrBuilder FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002748 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002749 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002750 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002751 bool UnnamedAddr;
2752 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002753
Chris Lattner1afcace2011-07-09 17:41:24 +00002754 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002755 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2756 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002757 ParseOptionalAttrs(FuncAttrs, 2) ||
2758 (EatIfPresent(lltok::kw_section) &&
2759 ParseStringConstant(Section)) ||
2760 ParseOptionalAlignment(Alignment) ||
2761 (EatIfPresent(lltok::kw_gc) &&
2762 ParseStringConstant(GC)))
2763 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002764
2765 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingf385f4c2012-10-08 23:27:46 +00002766 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendlingef99fe82012-09-21 15:26:31 +00002767 Alignment = FuncAttrs.getAlignment();
Bill Wendlingdc4efcb2012-10-09 09:17:28 +00002768 FuncAttrs.removeAttribute(Attributes::Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00002769 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002770
Chris Lattnerdf986172009-01-02 07:01:27 +00002771 // Okay, if we got here, the function is syntactically valid. Convert types
2772 // and do semantic checks.
Jay Foad5fdd6c82011-07-12 14:06:48 +00002773 std::vector<Type*> ParamTypeList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002774 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002775
Bill Wendlinge603fe42012-09-19 23:54:18 +00002776 if (RetAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00002777 Attrs.push_back(
2778 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
2779 Attributes::get(RetType->getContext(),
2780 RetAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002781
Chris Lattnerdf986172009-01-02 07:01:27 +00002782 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002783 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlinge603fe42012-09-19 23:54:18 +00002784 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00002785 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2786 }
2787
Bill Wendlinge603fe42012-09-19 23:54:18 +00002788 if (FuncAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00002789 Attrs.push_back(
2790 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
2791 Attributes::get(RetType->getContext(),
2792 FuncAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00002793
Chris Lattnerd509d0b2012-05-28 01:47:44 +00002794 AttrListPtr PAL = AttrListPtr::get(Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002795
Bill Wendling67658342012-10-09 07:45:08 +00002796 if (PAL.getParamAttributes(1).hasAttribute(Attributes::StructRet) &&
2797 !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002798 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2799
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002800 FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002801 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002802 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002803
2804 Fn = 0;
2805 if (!FunctionName.empty()) {
2806 // If this was a definition of a forward reference, remove the definition
2807 // from the forward reference table and fill in the forward ref.
2808 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2809 ForwardRefVals.find(FunctionName);
2810 if (FRVI != ForwardRefVals.end()) {
2811 Fn = M->getFunction(FunctionName);
Nick Lewycky64ea2752012-10-11 00:38:25 +00002812 if (!Fn)
2813 return Error(FRVI->second.second, "invalid forward reference to "
2814 "function as global value!");
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002815 if (Fn->getType() != PFT)
2816 return Error(FRVI->second.second, "invalid forward reference to "
2817 "function '" + FunctionName + "' with wrong type!");
2818
Chris Lattnerdf986172009-01-02 07:01:27 +00002819 ForwardRefVals.erase(FRVI);
2820 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002821 // Reject redefinitions.
2822 return Error(NameLoc, "invalid redefinition of function '" +
2823 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002824 } else if (M->getNamedValue(FunctionName)) {
2825 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002826 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002827
Dan Gohman41905542009-08-29 23:37:49 +00002828 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002829 // If this is a definition of a forward referenced function, make sure the
2830 // types agree.
2831 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2832 = ForwardRefValIDs.find(NumberedVals.size());
2833 if (I != ForwardRefValIDs.end()) {
2834 Fn = cast<Function>(I->second.first);
2835 if (Fn->getType() != PFT)
2836 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002837 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002838 ForwardRefValIDs.erase(I);
2839 }
2840 }
2841
2842 if (Fn == 0)
2843 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2844 else // Move the forward-reference to the correct spot in the module.
2845 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2846
2847 if (FunctionName.empty())
2848 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002849
Chris Lattnerdf986172009-01-02 07:01:27 +00002850 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2851 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2852 Fn->setCallingConv(CC);
2853 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002854 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002855 Fn->setAlignment(Alignment);
2856 Fn->setSection(Section);
2857 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002858
Chris Lattnerdf986172009-01-02 07:01:27 +00002859 // Add all of the arguments we parsed to the function.
2860 Function::arg_iterator ArgIt = Fn->arg_begin();
2861 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2862 // If the argument has a name, insert it into the argument symbol table.
2863 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002864
Chris Lattnerdf986172009-01-02 07:01:27 +00002865 // Set the name, if it conflicted, it will be auto-renamed.
2866 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002867
Benjamin Krameraf812352010-10-16 11:28:23 +00002868 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002869 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2870 ArgList[i].Name + "'");
2871 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002872
Chris Lattnerdf986172009-01-02 07:01:27 +00002873 return false;
2874}
2875
2876
2877/// ParseFunctionBody
2878/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002879///
2880bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002881 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002882 return TokError("expected '{' in function body");
2883 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002884
Chris Lattner09d9ef42009-10-28 03:39:23 +00002885 int FunctionNumber = -1;
2886 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2887
2888 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002889
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002890 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002891 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002892 return TokError("function body requires at least one basic block");
2893
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002894 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002895 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002896
Chris Lattnerdf986172009-01-02 07:01:27 +00002897 // Eat the }.
2898 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002899
Chris Lattnerdf986172009-01-02 07:01:27 +00002900 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002901 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002902}
2903
2904/// ParseBasicBlock
2905/// ::= LabelStr? Instruction*
2906bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2907 // If this basic block starts out with a name, remember it.
2908 std::string Name;
2909 LocTy NameLoc = Lex.getLoc();
2910 if (Lex.getKind() == lltok::LabelStr) {
2911 Name = Lex.getStrVal();
2912 Lex.Lex();
2913 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002914
Chris Lattnerdf986172009-01-02 07:01:27 +00002915 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2916 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002917
Chris Lattnerdf986172009-01-02 07:01:27 +00002918 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002919
Chris Lattnerdf986172009-01-02 07:01:27 +00002920 // Parse the instructions in this block until we get a terminator.
2921 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002922 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002923 do {
2924 // This instruction may have three possibilities for a name: a) none
2925 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2926 LocTy NameLoc = Lex.getLoc();
2927 int NameID = -1;
2928 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002929
Chris Lattnerdf986172009-01-02 07:01:27 +00002930 if (Lex.getKind() == lltok::LocalVarID) {
2931 NameID = Lex.getUIntVal();
2932 Lex.Lex();
2933 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2934 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002935 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002936 NameStr = Lex.getStrVal();
2937 Lex.Lex();
2938 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2939 return true;
2940 }
Devang Patelf633a062009-09-17 23:04:48 +00002941
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002942 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Topper85814382012-02-07 05:05:23 +00002943 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002944 case InstError: return true;
2945 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002946 BB->getInstList().push_back(Inst);
2947
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002948 // With a normal result, we check to see if the instruction is followed by
2949 // a comma and metadata.
2950 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002951 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002952 return true;
2953 break;
2954 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002955 BB->getInstList().push_back(Inst);
2956
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002957 // If the instruction parser ate an extra comma at the end of it, it
2958 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002959 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002960 return true;
2961 break;
2962 }
Devang Patelf633a062009-09-17 23:04:48 +00002963
Chris Lattnerdf986172009-01-02 07:01:27 +00002964 // Set the name on the instruction.
2965 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2966 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002967
Chris Lattnerdf986172009-01-02 07:01:27 +00002968 return false;
2969}
2970
2971//===----------------------------------------------------------------------===//
2972// Instruction Parsing.
2973//===----------------------------------------------------------------------===//
2974
2975/// ParseInstruction - Parse one of the many different instructions.
2976///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002977int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2978 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002979 lltok::Kind Token = Lex.getKind();
2980 if (Token == lltok::Eof)
2981 return TokError("found end of file when expecting more instructions");
2982 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002983 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002984 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002985
Chris Lattnerdf986172009-01-02 07:01:27 +00002986 switch (Token) {
2987 default: return Error(Loc, "expected instruction opcode");
2988 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002989 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002990 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2991 case lltok::kw_br: return ParseBr(Inst, PFS);
2992 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002993 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002994 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002995 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002996 // Binary Operators.
2997 case lltok::kw_add:
2998 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00002999 case lltok::kw_mul:
3000 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00003001 bool NUW = EatIfPresent(lltok::kw_nuw);
3002 bool NSW = EatIfPresent(lltok::kw_nsw);
3003 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3004
3005 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3006
3007 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3008 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3009 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00003010 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003011 case lltok::kw_fadd:
3012 case lltok::kw_fsub:
3013 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3014
Chris Lattner35bda892011-02-06 21:44:57 +00003015 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00003016 case lltok::kw_udiv:
3017 case lltok::kw_lshr:
3018 case lltok::kw_ashr: {
3019 bool Exact = EatIfPresent(lltok::kw_exact);
3020
3021 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3022 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3023 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00003024 }
3025
Chris Lattnerdf986172009-01-02 07:01:27 +00003026 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003027 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003028 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003029 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003030 case lltok::kw_and:
3031 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003032 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003033 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003034 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003035 // Casts.
3036 case lltok::kw_trunc:
3037 case lltok::kw_zext:
3038 case lltok::kw_sext:
3039 case lltok::kw_fptrunc:
3040 case lltok::kw_fpext:
3041 case lltok::kw_bitcast:
3042 case lltok::kw_uitofp:
3043 case lltok::kw_sitofp:
3044 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003045 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003046 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003047 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003048 // Other.
3049 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003050 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003051 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3052 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3053 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3054 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlinge6e88262011-08-12 20:24:12 +00003055 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003056 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3057 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3058 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003059 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003060 case lltok::kw_load: return ParseLoad(Inst, PFS);
3061 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedmanf03bb262011-08-12 22:50:01 +00003062 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3063 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedman47f35132011-07-25 23:16:38 +00003064 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003065 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3066 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3067 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3068 }
3069}
3070
3071/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3072bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003073 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003074 switch (Lex.getKind()) {
3075 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3076 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3077 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3078 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3079 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3080 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3081 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3082 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3083 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3084 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3085 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3086 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3087 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3088 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3089 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3090 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3091 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3092 }
3093 } else {
3094 switch (Lex.getKind()) {
3095 default: TokError("expected icmp predicate (e.g. 'eq')");
3096 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3097 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3098 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3099 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3100 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3101 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3102 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3103 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3104 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3105 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3106 }
3107 }
3108 Lex.Lex();
3109 return false;
3110}
3111
3112//===----------------------------------------------------------------------===//
3113// Terminator Instructions.
3114//===----------------------------------------------------------------------===//
3115
3116/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003117/// ::= 'ret' void (',' !dbg, !1)*
3118/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003119bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattner1afcace2011-07-09 17:41:24 +00003120 PerFunctionState &PFS) {
3121 SMLoc TypeLoc = Lex.getLoc();
3122 Type *Ty = 0;
Chris Lattnera9a9e072009-03-09 04:49:14 +00003123 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003124
Chris Lattner1afcace2011-07-09 17:41:24 +00003125 Type *ResType = PFS.getFunction().getReturnType();
3126
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003127 if (Ty->isVoidTy()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003128 if (!ResType->isVoidTy())
3129 return Error(TypeLoc, "value doesn't match function result type '" +
3130 getTypeString(ResType) + "'");
3131
Owen Anderson1d0be152009-08-13 21:58:54 +00003132 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003133 return false;
3134 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003135
Chris Lattnerdf986172009-01-02 07:01:27 +00003136 Value *RV;
3137 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003138
Chris Lattner1afcace2011-07-09 17:41:24 +00003139 if (ResType != RV->getType())
3140 return Error(TypeLoc, "value doesn't match function result type '" +
3141 getTypeString(ResType) + "'");
3142
Owen Anderson1d0be152009-08-13 21:58:54 +00003143 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003144 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003145}
3146
3147
3148/// ParseBr
3149/// ::= 'br' TypeAndValue
3150/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3151bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3152 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003153 Value *Op0;
3154 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003155 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003156
Chris Lattnerdf986172009-01-02 07:01:27 +00003157 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3158 Inst = BranchInst::Create(BB);
3159 return false;
3160 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003161
Owen Anderson1d0be152009-08-13 21:58:54 +00003162 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003163 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003164
Chris Lattnerdf986172009-01-02 07:01:27 +00003165 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003166 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003167 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003168 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003169 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003170
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003171 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003172 return false;
3173}
3174
3175/// ParseSwitch
3176/// Instruction
3177/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3178/// JumpTable
3179/// ::= (TypeAndValue ',' TypeAndValue)*
3180bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3181 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003182 Value *Cond;
3183 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003184 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3185 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003186 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003187 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3188 return true;
3189
Duncan Sands1df98592010-02-16 11:11:14 +00003190 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003191 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003192
Chris Lattnerdf986172009-01-02 07:01:27 +00003193 // Parse the jump table pairs.
3194 SmallPtrSet<Value*, 32> SeenCases;
3195 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3196 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003197 Value *Constant;
3198 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003199
Chris Lattnerdf986172009-01-02 07:01:27 +00003200 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3201 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003202 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003203 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003204
Chris Lattnerdf986172009-01-02 07:01:27 +00003205 if (!SeenCases.insert(Constant))
3206 return Error(CondLoc, "duplicate case value in switch");
3207 if (!isa<ConstantInt>(Constant))
3208 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003209
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003210 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003211 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003212
Chris Lattnerdf986172009-01-02 07:01:27 +00003213 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003214
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003215 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003216 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3217 SI->addCase(Table[i].first, Table[i].second);
3218 Inst = SI;
3219 return false;
3220}
3221
Chris Lattnerab21db72009-10-28 00:19:10 +00003222/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003223/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003224/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3225bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003226 LocTy AddrLoc;
3227 Value *Address;
3228 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003229 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3230 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003231 return true;
3232
Duncan Sands1df98592010-02-16 11:11:14 +00003233 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003234 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003235
3236 // Parse the destination list.
3237 SmallVector<BasicBlock*, 16> DestList;
3238
3239 if (Lex.getKind() != lltok::rsquare) {
3240 BasicBlock *DestBB;
3241 if (ParseTypeAndBasicBlock(DestBB, PFS))
3242 return true;
3243 DestList.push_back(DestBB);
3244
3245 while (EatIfPresent(lltok::comma)) {
3246 if (ParseTypeAndBasicBlock(DestBB, PFS))
3247 return true;
3248 DestList.push_back(DestBB);
3249 }
3250 }
3251
3252 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3253 return true;
3254
Chris Lattnerab21db72009-10-28 00:19:10 +00003255 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003256 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3257 IBI->addDestination(DestList[i]);
3258 Inst = IBI;
3259 return false;
3260}
3261
3262
Chris Lattnerdf986172009-01-02 07:01:27 +00003263/// ParseInvoke
3264/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3265/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3266bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3267 LocTy CallLoc = Lex.getLoc();
Bill Wendling702cc912012-10-15 20:35:56 +00003268 AttrBuilder RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003269 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003270 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003271 LocTy RetTypeLoc;
3272 ValID CalleeID;
3273 SmallVector<ParamInfo, 16> ArgList;
3274
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003275 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003276 if (ParseOptionalCallingConv(CC) ||
3277 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003278 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003279 ParseValID(CalleeID) ||
3280 ParseParameterList(ArgList, PFS) ||
3281 ParseOptionalAttrs(FnAttrs, 2) ||
3282 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003283 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003284 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003285 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003286 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003287
Chris Lattnerdf986172009-01-02 07:01:27 +00003288 // If RetType is a non-function pointer type, then this is the short syntax
3289 // for the call, which means that RetType is just the return type. Infer the
3290 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003291 PointerType *PFTy = 0;
3292 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003293 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3294 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3295 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003296 std::vector<Type*> ParamTypes;
Chris Lattnerdf986172009-01-02 07:01:27 +00003297 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3298 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003299
Chris Lattnerdf986172009-01-02 07:01:27 +00003300 if (!FunctionType::isValidReturnType(RetType))
3301 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003302
Owen Andersondebcb012009-07-29 22:17:13 +00003303 Ty = FunctionType::get(RetType, ParamTypes, false);
3304 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003305 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003306
Chris Lattnerdf986172009-01-02 07:01:27 +00003307 // Look up the callee.
3308 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003309 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003310
Chris Lattnerdf986172009-01-02 07:01:27 +00003311 // Set up the Attributes for the function.
3312 SmallVector<AttributeWithIndex, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003313 if (RetAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003314 Attrs.push_back(
3315 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
3316 Attributes::get(Callee->getContext(),
3317 RetAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003318
Chris Lattnerdf986172009-01-02 07:01:27 +00003319 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003320
Chris Lattnerdf986172009-01-02 07:01:27 +00003321 // Loop through FunctionType's arguments and ensure they are specified
3322 // correctly. Also, gather any parameter attributes.
3323 FunctionType::param_iterator I = Ty->param_begin();
3324 FunctionType::param_iterator E = Ty->param_end();
3325 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003326 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003327 if (I != E) {
3328 ExpectedTy = *I++;
3329 } else if (!Ty->isVarArg()) {
3330 return Error(ArgList[i].Loc, "too many arguments specified");
3331 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003332
Chris Lattnerdf986172009-01-02 07:01:27 +00003333 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3334 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003335 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003336 Args.push_back(ArgList[i].V);
Bill Wendlinge603fe42012-09-19 23:54:18 +00003337 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003338 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3339 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003340
Chris Lattnerdf986172009-01-02 07:01:27 +00003341 if (I != E)
3342 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003343
Bill Wendlinge603fe42012-09-19 23:54:18 +00003344 if (FnAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003345 Attrs.push_back(
3346 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
3347 Attributes::get(Callee->getContext(),
3348 FnAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003349
Chris Lattnerdf986172009-01-02 07:01:27 +00003350 // Finish off the Attributes and check them
Chris Lattnerd509d0b2012-05-28 01:47:44 +00003351 AttrListPtr PAL = AttrListPtr::get(Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003352
Jay Foada3efbb12011-07-15 08:37:34 +00003353 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003354 II->setCallingConv(CC);
3355 II->setAttributes(PAL);
3356 Inst = II;
3357 return false;
3358}
3359
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003360/// ParseResume
3361/// ::= 'resume' TypeAndValue
3362bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3363 Value *Exn; LocTy ExnLoc;
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003364 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3365 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003366
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003367 ResumeInst *RI = ResumeInst::Create(Exn);
3368 Inst = RI;
3369 return false;
3370}
Chris Lattnerdf986172009-01-02 07:01:27 +00003371
3372//===----------------------------------------------------------------------===//
3373// Binary Operators.
3374//===----------------------------------------------------------------------===//
3375
3376/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003377/// ::= ArithmeticOps TypeAndValue ',' Value
3378///
3379/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3380/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003381bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003382 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003383 LocTy Loc; Value *LHS, *RHS;
3384 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3385 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3386 ParseValue(LHS->getType(), RHS, PFS))
3387 return true;
3388
Chris Lattnere914b592009-01-05 08:24:46 +00003389 bool Valid;
3390 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003391 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003392 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003393 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3394 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003395 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003396 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3397 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003398 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003399
Chris Lattnere914b592009-01-05 08:24:46 +00003400 if (!Valid)
3401 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003402
Chris Lattnerdf986172009-01-02 07:01:27 +00003403 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3404 return false;
3405}
3406
3407/// ParseLogical
3408/// ::= ArithmeticOps TypeAndValue ',' Value {
3409bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3410 unsigned Opc) {
3411 LocTy Loc; Value *LHS, *RHS;
3412 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3413 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3414 ParseValue(LHS->getType(), RHS, PFS))
3415 return true;
3416
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003417 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003418 return Error(Loc,"instruction requires integer or integer vector operands");
3419
3420 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3421 return false;
3422}
3423
3424
3425/// ParseCompare
3426/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3427/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003428bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3429 unsigned Opc) {
3430 // Parse the integer/fp comparison predicate.
3431 LocTy Loc;
3432 unsigned Pred;
3433 Value *LHS, *RHS;
3434 if (ParseCmpPredicate(Pred, Opc) ||
3435 ParseTypeAndValue(LHS, Loc, PFS) ||
3436 ParseToken(lltok::comma, "expected ',' after compare value") ||
3437 ParseValue(LHS->getType(), RHS, PFS))
3438 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003439
Chris Lattnerdf986172009-01-02 07:01:27 +00003440 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003441 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003442 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003443 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003444 } else {
3445 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003446 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00003447 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003448 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003449 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003450 }
3451 return false;
3452}
3453
3454//===----------------------------------------------------------------------===//
3455// Other Instructions.
3456//===----------------------------------------------------------------------===//
3457
3458
3459/// ParseCast
3460/// ::= CastOpc TypeAndValue 'to' Type
3461bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3462 unsigned Opc) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003463 LocTy Loc;
3464 Value *Op;
3465 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003466 if (ParseTypeAndValue(Op, Loc, PFS) ||
3467 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3468 ParseType(DestTy))
3469 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003470
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003471 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3472 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003473 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003474 getTypeString(Op->getType()) + "' to '" +
3475 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003476 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003477 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3478 return false;
3479}
3480
3481/// ParseSelect
3482/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3483bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3484 LocTy Loc;
3485 Value *Op0, *Op1, *Op2;
3486 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3487 ParseToken(lltok::comma, "expected ',' after select condition") ||
3488 ParseTypeAndValue(Op1, PFS) ||
3489 ParseToken(lltok::comma, "expected ',' after select value") ||
3490 ParseTypeAndValue(Op2, PFS))
3491 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003492
Chris Lattnerdf986172009-01-02 07:01:27 +00003493 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3494 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003495
Chris Lattnerdf986172009-01-02 07:01:27 +00003496 Inst = SelectInst::Create(Op0, Op1, Op2);
3497 return false;
3498}
3499
Chris Lattner0088a5c2009-01-05 08:18:44 +00003500/// ParseVA_Arg
3501/// ::= 'va_arg' TypeAndValue ',' Type
3502bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003503 Value *Op;
Chris Lattner1afcace2011-07-09 17:41:24 +00003504 Type *EltTy = 0;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003505 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003506 if (ParseTypeAndValue(Op, PFS) ||
3507 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003508 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003509 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003510
Chris Lattner0088a5c2009-01-05 08:18:44 +00003511 if (!EltTy->isFirstClassType())
3512 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003513
3514 Inst = new VAArgInst(Op, EltTy);
3515 return false;
3516}
3517
3518/// ParseExtractElement
3519/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3520bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3521 LocTy Loc;
3522 Value *Op0, *Op1;
3523 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3524 ParseToken(lltok::comma, "expected ',' after extract value") ||
3525 ParseTypeAndValue(Op1, PFS))
3526 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003527
Chris Lattnerdf986172009-01-02 07:01:27 +00003528 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3529 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003530
Eric Christophera3500da2009-07-25 02:28:41 +00003531 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003532 return false;
3533}
3534
3535/// ParseInsertElement
3536/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3537bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3538 LocTy Loc;
3539 Value *Op0, *Op1, *Op2;
3540 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3541 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3542 ParseTypeAndValue(Op1, PFS) ||
3543 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3544 ParseTypeAndValue(Op2, PFS))
3545 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003546
Chris Lattnerdf986172009-01-02 07:01:27 +00003547 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003548 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003549
Chris Lattnerdf986172009-01-02 07:01:27 +00003550 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3551 return false;
3552}
3553
3554/// ParseShuffleVector
3555/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3556bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3557 LocTy Loc;
3558 Value *Op0, *Op1, *Op2;
3559 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3560 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3561 ParseTypeAndValue(Op1, PFS) ||
3562 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3563 ParseTypeAndValue(Op2, PFS))
3564 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003565
Chris Lattnerdf986172009-01-02 07:01:27 +00003566 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperaf393682012-02-01 23:43:12 +00003567 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003568
Chris Lattnerdf986172009-01-02 07:01:27 +00003569 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3570 return false;
3571}
3572
3573/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003574/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003575int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003576 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003577 Value *Op0, *Op1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003578
Chris Lattner1afcace2011-07-09 17:41:24 +00003579 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003580 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3581 ParseValue(Ty, Op0, PFS) ||
3582 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003583 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003584 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3585 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003586
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003587 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003588 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3589 while (1) {
3590 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003591
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003592 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003593 break;
3594
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003595 if (Lex.getKind() == lltok::MetadataVar) {
3596 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003597 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003598 }
Devang Patela43d46f2009-10-16 18:45:49 +00003599
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003600 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003601 ParseValue(Ty, Op0, PFS) ||
3602 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003603 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003604 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3605 return true;
3606 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003607
Chris Lattnerdf986172009-01-02 07:01:27 +00003608 if (!Ty->isFirstClassType())
3609 return Error(TypeLoc, "phi node must have first class type");
3610
Jay Foad3ecfc862011-03-30 11:28:46 +00003611 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003612 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3613 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3614 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003615 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003616}
3617
Bill Wendlinge6e88262011-08-12 20:24:12 +00003618/// ParseLandingPad
3619/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3620/// Clause
3621/// ::= 'catch' TypeAndValue
3622/// ::= 'filter'
3623/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3624bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3625 Type *Ty = 0; LocTy TyLoc;
3626 Value *PersFn; LocTy PersFnLoc;
Bill Wendlinge6e88262011-08-12 20:24:12 +00003627
3628 if (ParseType(Ty, TyLoc) ||
3629 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3630 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3631 return true;
3632
3633 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3634 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3635
3636 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3637 LandingPadInst::ClauseType CT;
3638 if (EatIfPresent(lltok::kw_catch))
3639 CT = LandingPadInst::Catch;
3640 else if (EatIfPresent(lltok::kw_filter))
3641 CT = LandingPadInst::Filter;
3642 else
3643 return TokError("expected 'catch' or 'filter' clause type");
3644
3645 Value *V; LocTy VLoc;
3646 if (ParseTypeAndValue(V, VLoc, PFS)) {
3647 delete LP;
3648 return true;
3649 }
3650
Bill Wendling746c8822011-08-12 20:52:25 +00003651 // A 'catch' type expects a non-array constant. A filter clause expects an
3652 // array constant.
3653 if (CT == LandingPadInst::Catch) {
3654 if (isa<ArrayType>(V->getType()))
3655 Error(VLoc, "'catch' clause has an invalid type");
3656 } else {
3657 if (!isa<ArrayType>(V->getType()))
3658 Error(VLoc, "'filter' clause has an invalid type");
3659 }
3660
Bill Wendlinge6e88262011-08-12 20:24:12 +00003661 LP->addClause(V);
3662 }
3663
3664 Inst = LP;
3665 return false;
3666}
3667
Chris Lattnerdf986172009-01-02 07:01:27 +00003668/// ParseCall
3669/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3670/// ParameterList OptionalAttrs
3671bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3672 bool isTail) {
Bill Wendling702cc912012-10-15 20:35:56 +00003673 AttrBuilder RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003674 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003675 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003676 LocTy RetTypeLoc;
3677 ValID CalleeID;
3678 SmallVector<ParamInfo, 16> ArgList;
3679 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003680
Chris Lattnerdf986172009-01-02 07:01:27 +00003681 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3682 ParseOptionalCallingConv(CC) ||
3683 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003684 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003685 ParseValID(CalleeID) ||
3686 ParseParameterList(ArgList, PFS) ||
3687 ParseOptionalAttrs(FnAttrs, 2))
3688 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003689
Chris Lattnerdf986172009-01-02 07:01:27 +00003690 // If RetType is a non-function pointer type, then this is the short syntax
3691 // for the call, which means that RetType is just the return type. Infer the
3692 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003693 PointerType *PFTy = 0;
3694 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003695 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3696 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3697 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003698 std::vector<Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003699 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3700 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003701
Chris Lattnerdf986172009-01-02 07:01:27 +00003702 if (!FunctionType::isValidReturnType(RetType))
3703 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003704
Owen Andersondebcb012009-07-29 22:17:13 +00003705 Ty = FunctionType::get(RetType, ParamTypes, false);
3706 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003707 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003708
Chris Lattnerdf986172009-01-02 07:01:27 +00003709 // Look up the callee.
3710 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003711 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003712
Chris Lattnerdf986172009-01-02 07:01:27 +00003713 // Set up the Attributes for the function.
3714 SmallVector<AttributeWithIndex, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003715 if (RetAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003716 Attrs.push_back(
3717 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
3718 Attributes::get(Callee->getContext(),
3719 RetAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003720
Chris Lattnerdf986172009-01-02 07:01:27 +00003721 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003722
Chris Lattnerdf986172009-01-02 07:01:27 +00003723 // Loop through FunctionType's arguments and ensure they are specified
3724 // correctly. Also, gather any parameter attributes.
3725 FunctionType::param_iterator I = Ty->param_begin();
3726 FunctionType::param_iterator E = Ty->param_end();
3727 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003728 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003729 if (I != E) {
3730 ExpectedTy = *I++;
3731 } else if (!Ty->isVarArg()) {
3732 return Error(ArgList[i].Loc, "too many arguments specified");
3733 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003734
Chris Lattnerdf986172009-01-02 07:01:27 +00003735 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3736 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003737 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003738 Args.push_back(ArgList[i].V);
Bill Wendlinge603fe42012-09-19 23:54:18 +00003739 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003740 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3741 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003742
Chris Lattnerdf986172009-01-02 07:01:27 +00003743 if (I != E)
3744 return Error(CallLoc, "not enough parameters specified for call");
3745
Bill Wendlinge603fe42012-09-19 23:54:18 +00003746 if (FnAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003747 Attrs.push_back(
3748 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
3749 Attributes::get(Callee->getContext(),
3750 FnAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00003751
3752 // Finish off the Attributes and check them
Chris Lattnerd509d0b2012-05-28 01:47:44 +00003753 AttrListPtr PAL = AttrListPtr::get(Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003754
Jay Foada3efbb12011-07-15 08:37:34 +00003755 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003756 CI->setTailCall(isTail);
3757 CI->setCallingConv(CC);
3758 CI->setAttributes(PAL);
3759 Inst = CI;
3760 return false;
3761}
3762
3763//===----------------------------------------------------------------------===//
3764// Memory Instructions.
3765//===----------------------------------------------------------------------===//
3766
3767/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003768/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003769int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003770 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003771 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003772 unsigned Alignment = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00003773 Type *Ty = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003774 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003775
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003776 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003777 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003778 if (Lex.getKind() == lltok::kw_align) {
3779 if (ParseOptionalAlignment(Alignment)) return true;
3780 } else if (Lex.getKind() == lltok::MetadataVar) {
3781 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003782 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003783 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3784 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3785 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003786 }
3787 }
3788
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003789 if (Size && !Size->getType()->isIntegerTy())
3790 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003791
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003792 Inst = new AllocaInst(Ty, Size, Alignment);
3793 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003794}
3795
3796/// ParseLoad
Eli Friedmanf03bb262011-08-12 22:50:01 +00003797/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3798/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3799/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003800int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003801 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003802 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003803 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003804 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003805 AtomicOrdering Ordering = NotAtomic;
3806 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003807
3808 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003809 isAtomic = true;
3810 Lex.Lex();
3811 }
3812
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003813 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003814 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003815 isVolatile = true;
3816 Lex.Lex();
3817 }
3818
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003819 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003820 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003821 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3822 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003823
Duncan Sands1df98592010-02-16 11:11:14 +00003824 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003825 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3826 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman21006d42011-08-09 23:02:53 +00003827 if (isAtomic && !Alignment)
3828 return Error(Loc, "atomic load must have explicit non-zero alignment");
3829 if (Ordering == Release || Ordering == AcquireRelease)
3830 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003831
Eli Friedman21006d42011-08-09 23:02:53 +00003832 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003833 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003834}
3835
3836/// ParseStore
Eli Friedmanf03bb262011-08-12 22:50:01 +00003837
3838/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3839/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman21006d42011-08-09 23:02:53 +00003840/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003841int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003842 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003843 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003844 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003845 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003846 AtomicOrdering Ordering = NotAtomic;
3847 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003848
3849 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003850 isAtomic = true;
3851 Lex.Lex();
3852 }
3853
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003854 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003855 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003856 isVolatile = true;
3857 Lex.Lex();
3858 }
3859
Chris Lattnerdf986172009-01-02 07:01:27 +00003860 if (ParseTypeAndValue(Val, Loc, PFS) ||
3861 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003862 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003863 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003864 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003865 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003866
Duncan Sands1df98592010-02-16 11:11:14 +00003867 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003868 return Error(PtrLoc, "store operand must be a pointer");
3869 if (!Val->getType()->isFirstClassType())
3870 return Error(Loc, "store operand must be a first class value");
3871 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3872 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman21006d42011-08-09 23:02:53 +00003873 if (isAtomic && !Alignment)
3874 return Error(Loc, "atomic store must have explicit non-zero alignment");
3875 if (Ordering == Acquire || Ordering == AcquireRelease)
3876 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003877
Eli Friedman21006d42011-08-09 23:02:53 +00003878 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003879 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003880}
3881
Eli Friedmanff030482011-07-28 21:48:00 +00003882/// ParseCmpXchg
Eli Friedmanf03bb262011-08-12 22:50:01 +00003883/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3884/// 'singlethread'? AtomicOrdering
3885int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003886 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3887 bool AteExtraComma = false;
3888 AtomicOrdering Ordering = NotAtomic;
3889 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003890 bool isVolatile = false;
3891
3892 if (EatIfPresent(lltok::kw_volatile))
3893 isVolatile = true;
3894
Eli Friedmanff030482011-07-28 21:48:00 +00003895 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3896 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3897 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3898 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3899 ParseTypeAndValue(New, NewLoc, PFS) ||
3900 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3901 return true;
3902
3903 if (Ordering == Unordered)
3904 return TokError("cmpxchg cannot be unordered");
3905 if (!Ptr->getType()->isPointerTy())
3906 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3907 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3908 return Error(CmpLoc, "compare value and pointer type do not match");
3909 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3910 return Error(NewLoc, "new value and pointer type do not match");
3911 if (!New->getType()->isIntegerTy())
3912 return Error(NewLoc, "cmpxchg operand must be an integer");
3913 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3914 if (Size < 8 || (Size & (Size - 1)))
3915 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3916 " integer");
3917
3918 AtomicCmpXchgInst *CXI =
3919 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3920 CXI->setVolatile(isVolatile);
3921 Inst = CXI;
3922 return AteExtraComma ? InstExtraComma : InstNormal;
3923}
3924
3925/// ParseAtomicRMW
Eli Friedmanf03bb262011-08-12 22:50:01 +00003926/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3927/// 'singlethread'? AtomicOrdering
3928int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003929 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3930 bool AteExtraComma = false;
3931 AtomicOrdering Ordering = NotAtomic;
3932 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003933 bool isVolatile = false;
Eli Friedmanff030482011-07-28 21:48:00 +00003934 AtomicRMWInst::BinOp Operation;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003935
3936 if (EatIfPresent(lltok::kw_volatile))
3937 isVolatile = true;
3938
Eli Friedmanff030482011-07-28 21:48:00 +00003939 switch (Lex.getKind()) {
3940 default: return TokError("expected binary operation in atomicrmw");
3941 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3942 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3943 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3944 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3945 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3946 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3947 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3948 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3949 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3950 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3951 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3952 }
3953 Lex.Lex(); // Eat the operation.
3954
3955 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3956 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3957 ParseTypeAndValue(Val, ValLoc, PFS) ||
3958 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3959 return true;
3960
3961 if (Ordering == Unordered)
3962 return TokError("atomicrmw cannot be unordered");
3963 if (!Ptr->getType()->isPointerTy())
3964 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3965 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3966 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3967 if (!Val->getType()->isIntegerTy())
3968 return Error(ValLoc, "atomicrmw operand must be an integer");
3969 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3970 if (Size < 8 || (Size & (Size - 1)))
3971 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3972 " integer");
3973
3974 AtomicRMWInst *RMWI =
3975 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3976 RMWI->setVolatile(isVolatile);
3977 Inst = RMWI;
3978 return AteExtraComma ? InstExtraComma : InstNormal;
3979}
3980
Eli Friedman47f35132011-07-25 23:16:38 +00003981/// ParseFence
3982/// ::= 'fence' 'singlethread'? AtomicOrdering
3983int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3984 AtomicOrdering Ordering = NotAtomic;
3985 SynchronizationScope Scope = CrossThread;
3986 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3987 return true;
3988
3989 if (Ordering == Unordered)
3990 return TokError("fence cannot be unordered");
3991 if (Ordering == Monotonic)
3992 return TokError("fence cannot be monotonic");
3993
3994 Inst = new FenceInst(Context, Ordering, Scope);
3995 return InstNormal;
3996}
3997
Chris Lattnerdf986172009-01-02 07:01:27 +00003998/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003999/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004000int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Nadav Rotem16087692011-12-05 06:29:09 +00004001 Value *Ptr = 0;
4002 Value *Val = 0;
4003 LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00004004
Dan Gohmandcb40a32009-07-29 15:58:36 +00004005 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00004006
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004007 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00004008
Nadav Rotem16087692011-12-05 06:29:09 +00004009 if (!Ptr->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00004010 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004011
Chris Lattnerdf986172009-01-02 07:01:27 +00004012 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004013 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004014 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004015 if (Lex.getKind() == lltok::MetadataVar) {
4016 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00004017 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004018 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004019 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem16087692011-12-05 06:29:09 +00004020 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00004021 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem16087692011-12-05 06:29:09 +00004022 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4023 return Error(EltLoc, "getelementptr index type missmatch");
4024 if (Val->getType()->isVectorTy()) {
4025 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4026 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4027 if (ValNumEl != PtrNumEl)
4028 return Error(EltLoc,
4029 "getelementptr vector index has a wrong number of elements");
4030 }
Chris Lattnerdf986172009-01-02 07:01:27 +00004031 Indices.push_back(Val);
4032 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00004033
Jay Foada9203102011-07-25 09:48:08 +00004034 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004035 return Error(Loc, "invalid getelementptr indices");
Jay Foada9203102011-07-25 09:48:08 +00004036 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohmandd8004d2009-07-27 21:53:46 +00004037 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004038 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004039 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004040}
4041
4042/// ParseExtractValue
4043/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004044int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004045 Value *Val; LocTy Loc;
4046 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004047 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004048 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004049 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004050 return true;
4051
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004052 if (!Val->getType()->isAggregateType())
4053 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00004054
Jay Foadfc6d3a42011-07-13 10:26:04 +00004055 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004056 return Error(Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004057 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004058 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004059}
4060
4061/// ParseInsertValue
4062/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004063int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004064 Value *Val0, *Val1; LocTy Loc0, Loc1;
4065 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004066 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004067 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4068 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4069 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004070 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004071 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00004072
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004073 if (!Val0->getType()->isAggregateType())
4074 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004075
Jay Foadfc6d3a42011-07-13 10:26:04 +00004076 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004077 return Error(Loc0, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004078 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004079 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004080}
Nick Lewycky21cc4462009-04-04 07:22:01 +00004081
4082//===----------------------------------------------------------------------===//
4083// Embedded metadata.
4084//===----------------------------------------------------------------------===//
4085
4086/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00004087/// ::= Element (',' Element)*
4088/// Element
4089/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00004090bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00004091 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00004092 // Check for an empty list.
4093 if (Lex.getKind() == lltok::rbrace)
4094 return false;
4095
Nick Lewycky21cc4462009-04-04 07:22:01 +00004096 do {
Chris Lattnera7352392009-12-30 04:42:57 +00004097 // Null is a special case since it is typeless.
4098 if (EatIfPresent(lltok::kw_null)) {
4099 Elts.push_back(0);
4100 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00004101 }
Chris Lattnera7352392009-12-30 04:42:57 +00004102
4103 Value *V = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00004104 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00004105 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004106 } while (EatIfPresent(lltok::comma));
4107
4108 return false;
4109}