blob: 327ce75db0eaf45b4dd040296d2c1dda1eceb634 [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;
Michael Ilseman407a6162012-11-15 22:34:00 +000055
Chris Lattner449c3102010-04-01 05:14:45 +000056 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
Michael Ilseman407a6162012-11-15 22:34:00 +000058
Chris Lattner449c3102010-04-01 05:14:45 +000059 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +000061 Twine(SlotNo) + "'");
Chris Lattner449c3102010-04-01 05:14:45 +000062 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
63 }
64 }
65 ForwardRefInstMetadata.clear();
66 }
Michael Ilseman407a6162012-11-15 22:34:00 +000067
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]);
Michael Ilseman407a6162012-11-15 22:34:00 +000079
Chris Lattner09d9ef42009-10-28 03:39:23 +000080 if (TheFn == 0)
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
Michael Ilseman407a6162012-11-15 22:34:00 +000082
Chris Lattner09d9ef42009-10-28 03:39:23 +000083 // Resolve all these references.
Michael Ilseman407a6162012-11-15 22:34:00 +000084 if (ResolveForwardRefBlockAddresses(TheFn,
Chris Lattner09d9ef42009-10-28 03:39:23 +000085 ForwardRefBlockAddresses.begin()->second,
86 0))
87 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +000088
Chris Lattner09d9ef42009-10-28 03:39:23 +000089 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
90 }
Michael Ilseman407a6162012-11-15 22:34:00 +000091
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
Michael Ilseman407a6162012-11-15 22:34:00 +0000126bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
Chris Lattner09d9ef42009-10-28 03:39:23 +0000127 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 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000144
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");
Michael Ilseman407a6162012-11-15 22:34:00 +0000148
Chris Lattner09d9ef42009-10-28 03:39:23 +0000149 // 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);
Michael Ilseman407a6162012-11-15 22:34:00 +0000305
Chris Lattner1afcace2011-07-09 17:41:24 +0000306 Type *Result = 0;
307 if (ParseStructDefinition(TypeLoc, "",
308 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000309
Chris Lattner1afcace2011-07-09 17:41:24 +0000310 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;
Michael Ilseman407a6162012-11-15 22:34:00 +0000332
Chris Lattner1afcace2011-07-09 17:41:24 +0000333 Type *Result = 0;
334 if (ParseStructDefinition(NameLoc, Name,
335 NamedTypes[Name], Result)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000336
Chris Lattner1afcace2011-07-09 17:41:24 +0000337 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 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000344
Chris Lattner1afcace2011-07-09 17:41:24 +0000345 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());
Michael Ilseman407a6162012-11-15 22:34:00 +0000476
Chris Lattner0834e6a2009-12-30 04:51:58 +0000477 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;
Michael Ilseman407a6162012-11-15 22:34:00 +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);
Michael Ilseman407a6162012-11-15 22:34:00 +0000533
Chris Lattner0834e6a2009-12-30 04:51:58 +0000534 // 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);
Michael Ilseman407a6162012-11-15 22:34:00 +0000542
Chris Lattner0834e6a2009-12-30 04:51:58 +0000543 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,
Justin Holewinskieaff2d52012-11-16 21:03:47 +0000782 GlobalValue::ExternalWeakLinkage, 0, Name,
783 0, GlobalVariable::NotThreadLocal,
784 PTy->getAddressSpace());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000785
Chris Lattnerdf986172009-01-02 07:01:27 +0000786 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
787 return FwdVal;
788}
789
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000790GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
791 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000792 if (PTy == 0) {
793 Error(Loc, "global variable reference must have pointer type");
794 return 0;
795 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000796
Chris Lattnerdf986172009-01-02 07:01:27 +0000797 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000798
Chris Lattnerdf986172009-01-02 07:01:27 +0000799 // If this is a forward reference for the value, see if we already created a
800 // forward ref record.
801 if (Val == 0) {
802 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
803 I = ForwardRefValIDs.find(ID);
804 if (I != ForwardRefValIDs.end())
805 Val = I->second.first;
806 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000807
Chris Lattnerdf986172009-01-02 07:01:27 +0000808 // If we have the value in the symbol table or fwd-ref table, return it.
809 if (Val) {
810 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000811 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000812 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000813 return 0;
814 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000815
Chris Lattnerdf986172009-01-02 07:01:27 +0000816 // Otherwise, create a new forward reference for this value and remember it.
817 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000818 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000819 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000820 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000821 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
822 GlobalValue::ExternalWeakLinkage, 0, "");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000823
Chris Lattnerdf986172009-01-02 07:01:27 +0000824 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
825 return FwdVal;
826}
827
828
829//===----------------------------------------------------------------------===//
830// Helper Routines.
831//===----------------------------------------------------------------------===//
832
833/// ParseToken - If the current token has the specified kind, eat it and return
834/// success. Otherwise, emit the specified error and return failure.
835bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
836 if (Lex.getKind() != T)
837 return TokError(ErrMsg);
838 Lex.Lex();
839 return false;
840}
841
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000842/// ParseStringConstant
843/// ::= StringConstant
844bool LLParser::ParseStringConstant(std::string &Result) {
845 if (Lex.getKind() != lltok::StringConstant)
846 return TokError("expected string constant");
847 Result = Lex.getStrVal();
848 Lex.Lex();
849 return false;
850}
851
852/// ParseUInt32
853/// ::= uint32
854bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000855 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
856 return TokError("expected integer");
857 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
858 if (Val64 != unsigned(Val64))
859 return TokError("expected 32-bit integer (too large)");
860 Val = Val64;
861 Lex.Lex();
862 return false;
863}
864
Hans Wennborgce718ff2012-06-23 11:37:03 +0000865/// ParseTLSModel
866/// := 'localdynamic'
867/// := 'initialexec'
868/// := 'localexec'
869bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
870 switch (Lex.getKind()) {
871 default:
872 return TokError("expected localdynamic, initialexec or localexec");
873 case lltok::kw_localdynamic:
874 TLM = GlobalVariable::LocalDynamicTLSModel;
875 break;
876 case lltok::kw_initialexec:
877 TLM = GlobalVariable::InitialExecTLSModel;
878 break;
879 case lltok::kw_localexec:
880 TLM = GlobalVariable::LocalExecTLSModel;
881 break;
882 }
883
884 Lex.Lex();
885 return false;
886}
887
888/// ParseOptionalThreadLocal
889/// := /*empty*/
890/// := 'thread_local'
891/// := 'thread_local' '(' tlsmodel ')'
892bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
893 TLM = GlobalVariable::NotThreadLocal;
894 if (!EatIfPresent(lltok::kw_thread_local))
895 return false;
896
897 TLM = GlobalVariable::GeneralDynamicTLSModel;
898 if (Lex.getKind() == lltok::lparen) {
899 Lex.Lex();
900 return ParseTLSModel(TLM) ||
901 ParseToken(lltok::rparen, "expected ')' after thread local model");
902 }
903 return false;
904}
Chris Lattnerdf986172009-01-02 07:01:27 +0000905
906/// ParseOptionalAddrSpace
907/// := /*empty*/
908/// := 'addrspace' '(' uint32 ')'
909bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
910 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000911 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000912 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000913 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000914 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000915 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000916}
Chris Lattnerdf986172009-01-02 07:01:27 +0000917
918/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
919/// indicates what kind of attribute list this is: 0: function arg, 1: result,
920/// 2: function attr.
Bill Wendling702cc912012-10-15 20:35:56 +0000921bool LLParser::ParseOptionalAttrs(AttrBuilder &B, unsigned AttrKind) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000922 LocTy AttrLoc = Lex.getLoc();
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000923 bool HaveError = false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000924
Bill Wendlingf385f4c2012-10-08 23:27:46 +0000925 B.clear();
926
Chris Lattnerdf986172009-01-02 07:01:27 +0000927 while (1) {
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000928 lltok::Kind Token = Lex.getKind();
929 switch (Token) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000930 default: // End of attributes.
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000931 return HaveError;
Bill Wendling2e879bc2012-10-09 09:11:20 +0000932 case lltok::kw_zeroext: B.addAttribute(Attributes::ZExt); break;
933 case lltok::kw_signext: B.addAttribute(Attributes::SExt); break;
934 case lltok::kw_inreg: B.addAttribute(Attributes::InReg); break;
935 case lltok::kw_sret: B.addAttribute(Attributes::StructRet); break;
936 case lltok::kw_noalias: B.addAttribute(Attributes::NoAlias); break;
937 case lltok::kw_nocapture: B.addAttribute(Attributes::NoCapture); break;
938 case lltok::kw_byval: B.addAttribute(Attributes::ByVal); break;
939 case lltok::kw_nest: B.addAttribute(Attributes::Nest); break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000940
Bill Wendling2e879bc2012-10-09 09:11:20 +0000941 case lltok::kw_noreturn: B.addAttribute(Attributes::NoReturn); break;
942 case lltok::kw_nounwind: B.addAttribute(Attributes::NoUnwind); break;
943 case lltok::kw_uwtable: B.addAttribute(Attributes::UWTable); break;
944 case lltok::kw_returns_twice: B.addAttribute(Attributes::ReturnsTwice); break;
945 case lltok::kw_noinline: B.addAttribute(Attributes::NoInline); break;
946 case lltok::kw_readnone: B.addAttribute(Attributes::ReadNone); break;
947 case lltok::kw_readonly: B.addAttribute(Attributes::ReadOnly); break;
948 case lltok::kw_inlinehint: B.addAttribute(Attributes::InlineHint); break;
949 case lltok::kw_alwaysinline: B.addAttribute(Attributes::AlwaysInline); break;
950 case lltok::kw_optsize: B.addAttribute(Attributes::OptimizeForSize); break;
951 case lltok::kw_ssp: B.addAttribute(Attributes::StackProtect); break;
952 case lltok::kw_sspreq: B.addAttribute(Attributes::StackProtectReq); break;
953 case lltok::kw_noredzone: B.addAttribute(Attributes::NoRedZone); break;
954 case lltok::kw_noimplicitfloat: B.addAttribute(Attributes::NoImplicitFloat); break;
955 case lltok::kw_naked: B.addAttribute(Attributes::Naked); break;
956 case lltok::kw_nonlazybind: B.addAttribute(Attributes::NonLazyBind); break;
957 case lltok::kw_address_safety: B.addAttribute(Attributes::AddressSafety); break;
Quentin Colombet9a419f62012-10-30 16:32:52 +0000958 case lltok::kw_minsize: B.addAttribute(Attributes::MinSize); break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000959
Charles Davis1e063d12010-02-12 00:31:15 +0000960 case lltok::kw_alignstack: {
961 unsigned Alignment;
962 if (ParseOptionalStackAlignment(Alignment))
963 return true;
Bill Wendling03272442012-10-08 22:20:14 +0000964 B.addStackAlignmentAttr(Alignment);
Charles Davis1e063d12010-02-12 00:31:15 +0000965 continue;
966 }
967
Chris Lattnerdf986172009-01-02 07:01:27 +0000968 case lltok::kw_align: {
969 unsigned Alignment;
970 if (ParseOptionalAlignment(Alignment))
971 return true;
Bill Wendling03272442012-10-08 22:20:14 +0000972 B.addAlignmentAttr(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000973 continue;
974 }
Charles Davis1e063d12010-02-12 00:31:15 +0000975
Chris Lattnerdf986172009-01-02 07:01:27 +0000976 }
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000977
978 // Perform some error checking.
979 switch (Token) {
980 default:
981 if (AttrKind == 2)
982 HaveError |= Error(AttrLoc, "invalid use of attribute on a function");
983 break;
984 case lltok::kw_align:
985 // As a hack, we allow "align 2" on functions as a synonym for
986 // "alignstack 2".
987 break;
988
989 // Parameter Only:
990 case lltok::kw_sret:
991 case lltok::kw_nocapture:
992 case lltok::kw_byval:
993 case lltok::kw_nest:
994 if (AttrKind != 0)
995 HaveError |= Error(AttrLoc, "invalid use of parameter-only attribute");
996 break;
997
998 // Function Only:
999 case lltok::kw_noreturn:
1000 case lltok::kw_nounwind:
1001 case lltok::kw_readnone:
1002 case lltok::kw_readonly:
1003 case lltok::kw_noinline:
1004 case lltok::kw_alwaysinline:
1005 case lltok::kw_optsize:
1006 case lltok::kw_ssp:
1007 case lltok::kw_sspreq:
1008 case lltok::kw_noredzone:
1009 case lltok::kw_noimplicitfloat:
1010 case lltok::kw_naked:
1011 case lltok::kw_inlinehint:
1012 case lltok::kw_alignstack:
1013 case lltok::kw_uwtable:
1014 case lltok::kw_nonlazybind:
1015 case lltok::kw_returns_twice:
1016 case lltok::kw_address_safety:
Quentin Colombet9a419f62012-10-30 16:32:52 +00001017 case lltok::kw_minsize:
Bill Wendlingdc998cc2012-09-28 22:30:18 +00001018 if (AttrKind != 2)
1019 HaveError |= Error(AttrLoc, "invalid use of function-only attribute");
1020 break;
1021 }
1022
Chris Lattnerdf986172009-01-02 07:01:27 +00001023 Lex.Lex();
1024 }
1025}
1026
1027/// ParseOptionalLinkage
1028/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001029/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001030/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001031/// ::= 'linker_private_weak'
Chris Lattnerdf986172009-01-02 07:01:27 +00001032/// ::= 'internal'
1033/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001034/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001035/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001036/// ::= 'linkonce_odr'
Bill Wendling32811be2012-08-17 18:33:14 +00001037/// ::= 'linkonce_odr_auto_hide'
Bill Wendling5e721d72010-07-01 21:55:59 +00001038/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001039/// ::= 'appending'
1040/// ::= 'dllexport'
1041/// ::= 'common'
1042/// ::= 'dllimport'
1043/// ::= 'extern_weak'
1044/// ::= 'external'
1045bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1046 HasLinkage = false;
1047 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001048 default: Res=GlobalValue::ExternalLinkage; return false;
1049 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1050 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001051 case lltok::kw_linker_private_weak:
1052 Res = GlobalValue::LinkerPrivateWeakLinkage;
1053 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001054 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1055 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1056 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1057 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1058 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Bill Wendling32811be2012-08-17 18:33:14 +00001059 case lltok::kw_linkonce_odr_auto_hide:
1060 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1061 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1062 break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001063 case lltok::kw_available_externally:
1064 Res = GlobalValue::AvailableExternallyLinkage;
1065 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001066 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1067 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1068 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1069 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1070 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1071 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001072 }
1073 Lex.Lex();
1074 HasLinkage = true;
1075 return false;
1076}
1077
1078/// ParseOptionalVisibility
1079/// ::= /*empty*/
1080/// ::= 'default'
1081/// ::= 'hidden'
1082/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001083///
Chris Lattnerdf986172009-01-02 07:01:27 +00001084bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1085 switch (Lex.getKind()) {
1086 default: Res = GlobalValue::DefaultVisibility; return false;
1087 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1088 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1089 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1090 }
1091 Lex.Lex();
1092 return false;
1093}
1094
1095/// ParseOptionalCallingConv
1096/// ::= /*empty*/
1097/// ::= 'ccc'
1098/// ::= 'fastcc'
Elena Demikhovsky35752222012-10-24 14:46:16 +00001099/// ::= 'kw_intel_ocl_bicc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001100/// ::= 'coldcc'
1101/// ::= 'x86_stdcallcc'
1102/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001103/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001104/// ::= 'arm_apcscc'
1105/// ::= 'arm_aapcscc'
1106/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001107/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001108/// ::= 'ptx_kernel'
1109/// ::= 'ptx_device'
Micah Villmowe53d6052012-10-01 17:01:31 +00001110/// ::= 'spir_func'
1111/// ::= 'spir_kernel'
Chris Lattnerdf986172009-01-02 07:01:27 +00001112/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001113///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001114bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001115 switch (Lex.getKind()) {
1116 default: CC = CallingConv::C; return false;
1117 case lltok::kw_ccc: CC = CallingConv::C; break;
1118 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1119 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1120 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1121 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001122 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001123 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1124 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1125 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001126 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001127 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1128 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmowe53d6052012-10-01 17:01:31 +00001129 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1130 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovsky35752222012-10-24 14:46:16 +00001131 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001132 case lltok::kw_cc: {
1133 unsigned ArbitraryCC;
1134 Lex.Lex();
David Blaikie4d6ccb52012-01-20 21:51:11 +00001135 if (ParseUInt32(ArbitraryCC))
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001136 return true;
David Blaikie4d6ccb52012-01-20 21:51:11 +00001137 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1138 return false;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001139 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001140 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001141
Chris Lattnerdf986172009-01-02 07:01:27 +00001142 Lex.Lex();
1143 return false;
1144}
1145
Chris Lattnerb8c46862009-12-30 05:31:19 +00001146/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001147/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001148bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1149 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001150 do {
1151 if (Lex.getKind() != lltok::MetadataVar)
1152 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001153
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001154 std::string Name = Lex.getStrVal();
Benjamin Kramer85dadec2011-12-06 11:50:26 +00001155 unsigned MDK = M->getMDKindID(Name);
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001156 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001157
Chris Lattner442ffa12009-12-29 21:53:55 +00001158 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001159 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001160
1161 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001162 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001163
Dan Gohman68261142010-08-24 14:35:45 +00001164 // This code is similar to that of ParseMetadataValue, however it needs to
1165 // have special-case code for a forward reference; see the comments on
1166 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1167 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001168 if (Lex.getKind() == lltok::lbrace) {
1169 ValID ID;
1170 if (ParseMetadataListValue(ID, PFS))
1171 return true;
1172 assert(ID.Kind == ValID::t_MDNode);
1173 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001174 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001175 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001176 if (ParseMDNodeID(Node, NodeID))
1177 return true;
1178 if (Node) {
1179 // If we got the node, add it to the instruction.
1180 Inst->setMetadata(MDK, Node);
1181 } else {
1182 MDRef R = { Loc, MDK, NodeID };
1183 // Otherwise, remember that this should be resolved later.
1184 ForwardRefInstMetadata[Inst].push_back(R);
1185 }
Chris Lattner449c3102010-04-01 05:14:45 +00001186 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001187
1188 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001189 } while (EatIfPresent(lltok::comma));
1190 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001191}
1192
Chris Lattnerdf986172009-01-02 07:01:27 +00001193/// ParseOptionalAlignment
1194/// ::= /* empty */
1195/// ::= 'align' 4
1196bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1197 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001198 if (!EatIfPresent(lltok::kw_align))
1199 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001200 LocTy AlignLoc = Lex.getLoc();
1201 if (ParseUInt32(Alignment)) return true;
1202 if (!isPowerOf2_32(Alignment))
1203 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001204 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001205 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001206 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001207}
1208
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001209/// ParseOptionalCommaAlign
Michael Ilseman407a6162012-11-15 22:34:00 +00001210/// ::=
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001211/// ::= ',' align 4
1212///
1213/// This returns with AteExtraComma set to true if it ate an excess comma at the
1214/// end.
1215bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1216 bool &AteExtraComma) {
1217 AteExtraComma = false;
1218 while (EatIfPresent(lltok::comma)) {
1219 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001220 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001221 AteExtraComma = true;
1222 return false;
1223 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001224
Chris Lattner093eed12010-04-23 00:50:50 +00001225 if (Lex.getKind() != lltok::kw_align)
1226 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001227
Chris Lattner093eed12010-04-23 00:50:50 +00001228 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001229 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001230
Devang Patelf633a062009-09-17 23:04:48 +00001231 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001232}
1233
Eli Friedman47f35132011-07-25 23:16:38 +00001234/// ParseScopeAndOrdering
1235/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1236/// else: ::=
1237///
1238/// This sets Scope and Ordering to the parsed values.
1239bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1240 AtomicOrdering &Ordering) {
1241 if (!isAtomic)
1242 return false;
1243
1244 Scope = CrossThread;
1245 if (EatIfPresent(lltok::kw_singlethread))
1246 Scope = SingleThread;
1247 switch (Lex.getKind()) {
1248 default: return TokError("Expected ordering on atomic instruction");
1249 case lltok::kw_unordered: Ordering = Unordered; break;
1250 case lltok::kw_monotonic: Ordering = Monotonic; break;
1251 case lltok::kw_acquire: Ordering = Acquire; break;
1252 case lltok::kw_release: Ordering = Release; break;
1253 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1254 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1255 }
1256 Lex.Lex();
1257 return false;
1258}
1259
Charles Davis1e063d12010-02-12 00:31:15 +00001260/// ParseOptionalStackAlignment
1261/// ::= /* empty */
1262/// ::= 'alignstack' '(' 4 ')'
1263bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1264 Alignment = 0;
1265 if (!EatIfPresent(lltok::kw_alignstack))
1266 return false;
1267 LocTy ParenLoc = Lex.getLoc();
1268 if (!EatIfPresent(lltok::lparen))
1269 return Error(ParenLoc, "expected '('");
1270 LocTy AlignLoc = Lex.getLoc();
1271 if (ParseUInt32(Alignment)) return true;
1272 ParenLoc = Lex.getLoc();
1273 if (!EatIfPresent(lltok::rparen))
1274 return Error(ParenLoc, "expected ')'");
1275 if (!isPowerOf2_32(Alignment))
1276 return Error(AlignLoc, "stack alignment is not a power of two");
1277 return false;
1278}
Devang Patelf633a062009-09-17 23:04:48 +00001279
Chris Lattner628c13a2009-12-30 05:14:00 +00001280/// ParseIndexList - This parses the index list for an insert/extractvalue
1281/// instruction. This sets AteExtraComma in the case where we eat an extra
1282/// comma at the end of the line and find that it is followed by metadata.
1283/// Clients that don't allow metadata can call the version of this function that
1284/// only takes one argument.
1285///
Chris Lattnerdf986172009-01-02 07:01:27 +00001286/// ParseIndexList
1287/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001288///
1289bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1290 bool &AteExtraComma) {
1291 AteExtraComma = false;
Michael Ilseman407a6162012-11-15 22:34:00 +00001292
Chris Lattnerdf986172009-01-02 07:01:27 +00001293 if (Lex.getKind() != lltok::comma)
1294 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001295
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001296 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001297 if (Lex.getKind() == lltok::MetadataVar) {
1298 AteExtraComma = true;
1299 return false;
1300 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001301 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001302 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001303 Indices.push_back(Idx);
1304 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001305
Chris Lattnerdf986172009-01-02 07:01:27 +00001306 return false;
1307}
1308
1309//===----------------------------------------------------------------------===//
1310// Type Parsing.
1311//===----------------------------------------------------------------------===//
1312
Chris Lattner1afcace2011-07-09 17:41:24 +00001313/// ParseType - Parse a type.
1314bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1315 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001316 switch (Lex.getKind()) {
1317 default:
1318 return TokError("expected type");
1319 case lltok::Type:
Chris Lattner1afcace2011-07-09 17:41:24 +00001320 // Type ::= 'float' | 'void' (etc)
Chris Lattnerdf986172009-01-02 07:01:27 +00001321 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001322 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001323 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001324 case lltok::lbrace:
Chris Lattner1afcace2011-07-09 17:41:24 +00001325 // Type ::= StructType
1326 if (ParseAnonStructType(Result, false))
Chris Lattnerdf986172009-01-02 07:01:27 +00001327 return true;
1328 break;
1329 case lltok::lsquare:
Chris Lattner1afcace2011-07-09 17:41:24 +00001330 // Type ::= '[' ... ']'
Chris Lattnerdf986172009-01-02 07:01:27 +00001331 Lex.Lex(); // eat the lsquare.
1332 if (ParseArrayVectorType(Result, false))
1333 return true;
1334 break;
1335 case lltok::less: // Either vector or packed struct.
Chris Lattner1afcace2011-07-09 17:41:24 +00001336 // Type ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001337 Lex.Lex();
1338 if (Lex.getKind() == lltok::lbrace) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001339 if (ParseAnonStructType(Result, true) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001340 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001341 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001342 } else if (ParseArrayVectorType(Result, true))
1343 return true;
1344 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001345 case lltok::LocalVar: {
1346 // Type ::= %foo
1347 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman407a6162012-11-15 22:34:00 +00001348
Chris Lattner1afcace2011-07-09 17:41:24 +00001349 // If the type hasn't been defined yet, create a forward definition and
1350 // remember where that forward def'n was seen (in case it never is defined).
1351 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001352 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattner1afcace2011-07-09 17:41:24 +00001353 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001354 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001355 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001356 Lex.Lex();
1357 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001358 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001359
Chris Lattner1afcace2011-07-09 17:41:24 +00001360 case lltok::LocalVarID: {
1361 // Type ::= %4
1362 if (Lex.getUIntVal() >= NumberedTypes.size())
1363 NumberedTypes.resize(Lex.getUIntVal()+1);
1364 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman407a6162012-11-15 22:34:00 +00001365
Chris Lattner1afcace2011-07-09 17:41:24 +00001366 // If the type hasn't been defined yet, create a forward definition and
1367 // remember where that forward def'n was seen (in case it never is defined).
1368 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001369 Entry.first = StructType::create(Context);
Chris Lattner1afcace2011-07-09 17:41:24 +00001370 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001371 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001372 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001373 Lex.Lex();
1374 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001375 }
1376 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001377
1378 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001379 while (1) {
1380 switch (Lex.getKind()) {
1381 // End of type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001382 default:
1383 if (!AllowVoid && Result->isVoidTy())
1384 return Error(TypeLoc, "void type only allowed for function results");
1385 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001386
Chris Lattner1afcace2011-07-09 17:41:24 +00001387 // Type ::= Type '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001388 case lltok::star:
Chris Lattner1afcace2011-07-09 17:41:24 +00001389 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001390 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001391 if (Result->isVoidTy())
1392 return TokError("pointers to void are invalid - use i8* instead");
1393 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001394 return TokError("pointer to this type is invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001395 Result = PointerType::getUnqual(Result);
Chris Lattnerdf986172009-01-02 07:01:27 +00001396 Lex.Lex();
1397 break;
1398
Chris Lattner1afcace2011-07-09 17:41:24 +00001399 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001400 case lltok::kw_addrspace: {
Chris Lattner1afcace2011-07-09 17:41:24 +00001401 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001402 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001403 if (Result->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001404 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattner1afcace2011-07-09 17:41:24 +00001405 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001406 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001407 unsigned AddrSpace;
1408 if (ParseOptionalAddrSpace(AddrSpace) ||
1409 ParseToken(lltok::star, "expected '*' in address space"))
1410 return true;
1411
Chris Lattner1afcace2011-07-09 17:41:24 +00001412 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001413 break;
1414 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001415
Chris Lattnerdf986172009-01-02 07:01:27 +00001416 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1417 case lltok::lparen:
1418 if (ParseFunctionType(Result))
1419 return true;
1420 break;
1421 }
1422 }
1423}
1424
1425/// ParseParameterList
1426/// ::= '(' ')'
1427/// ::= '(' Arg (',' Arg)* ')'
1428/// Arg
1429/// ::= Type OptionalAttributes Value OptionalAttributes
1430bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1431 PerFunctionState &PFS) {
1432 if (ParseToken(lltok::lparen, "expected '(' in call"))
1433 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001434
Chris Lattnerdf986172009-01-02 07:01:27 +00001435 while (Lex.getKind() != lltok::rparen) {
1436 // If this isn't the first argument, we need a comma.
1437 if (!ArgList.empty() &&
1438 ParseToken(lltok::comma, "expected ',' in argument list"))
1439 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001440
Chris Lattnerdf986172009-01-02 07:01:27 +00001441 // Parse the argument.
1442 LocTy ArgLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +00001443 Type *ArgTy = 0;
Bill Wendling702cc912012-10-15 20:35:56 +00001444 AttrBuilder ArgAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001445 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001446 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001447 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001448
Chris Lattner287881d2009-12-30 02:11:14 +00001449 // Otherwise, handle normal operands.
Bill Wendling03272442012-10-08 22:20:14 +00001450 if (ParseOptionalAttrs(ArgAttrs, 0) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001451 return true;
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001452 ArgList.push_back(ParamInfo(ArgLoc, V, Attributes::get(V->getContext(),
1453 ArgAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00001454 }
1455
1456 Lex.Lex(); // Lex the ')'.
1457 return false;
1458}
1459
1460
1461
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001462/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattner1afcace2011-07-09 17:41:24 +00001463/// prototype.
Chris Lattnerdf986172009-01-02 07:01:27 +00001464/// ::= '(' ArgTypeListI ')'
1465/// ArgTypeListI
1466/// ::= /*empty*/
1467/// ::= '...'
1468/// ::= ArgTypeList ',' '...'
1469/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001470///
Chris Lattner1afcace2011-07-09 17:41:24 +00001471bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1472 bool &isVarArg){
Chris Lattnerdf986172009-01-02 07:01:27 +00001473 isVarArg = false;
1474 assert(Lex.getKind() == lltok::lparen);
1475 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001476
Chris Lattnerdf986172009-01-02 07:01:27 +00001477 if (Lex.getKind() == lltok::rparen) {
1478 // empty
1479 } else if (Lex.getKind() == lltok::dotdotdot) {
1480 isVarArg = true;
1481 Lex.Lex();
1482 } else {
1483 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001484 Type *ArgTy = 0;
Bill Wendling702cc912012-10-15 20:35:56 +00001485 AttrBuilder Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001486 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001487
Chris Lattner1afcace2011-07-09 17:41:24 +00001488 if (ParseType(ArgTy) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001489 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001490
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001491 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001492 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001493
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001494 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001495 Name = Lex.getStrVal();
1496 Lex.Lex();
1497 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001498
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001499 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001500 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001501
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001502 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1503 Attributes::get(ArgTy->getContext(),
1504 Attrs), Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001505
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001506 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001507 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001508 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001509 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001510 break;
1511 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001512
Chris Lattnerdf986172009-01-02 07:01:27 +00001513 // Otherwise must be an argument type.
1514 TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001515 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001516
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001517 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001518 return Error(TypeLoc, "argument can not have void type");
1519
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001520 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001521 Name = Lex.getStrVal();
1522 Lex.Lex();
1523 } else {
1524 Name = "";
1525 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001526
Chris Lattner1afcace2011-07-09 17:41:24 +00001527 if (!ArgTy->isFirstClassType())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001528 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001529
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001530 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1531 Attributes::get(ArgTy->getContext(), Attrs),
1532 Name));
Chris Lattnerdf986172009-01-02 07:01:27 +00001533 }
1534 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001535
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001536 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001537}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001538
Chris Lattnerdf986172009-01-02 07:01:27 +00001539/// ParseFunctionType
1540/// ::= Type ArgumentList OptionalAttrs
Chris Lattner1afcace2011-07-09 17:41:24 +00001541bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001542 assert(Lex.getKind() == lltok::lparen);
1543
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001544 if (!FunctionType::isValidReturnType(Result))
1545 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001546
Chris Lattner1afcace2011-07-09 17:41:24 +00001547 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00001548 bool isVarArg;
Chris Lattner1afcace2011-07-09 17:41:24 +00001549 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerdf986172009-01-02 07:01:27 +00001550 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001551
Chris Lattnerdf986172009-01-02 07:01:27 +00001552 // Reject names on the arguments lists.
1553 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1554 if (!ArgList[i].Name.empty())
1555 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendling7be78482012-10-14 08:54:26 +00001556 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnera16546a2011-06-17 17:37:13 +00001557 return Error(ArgList[i].Loc,
1558 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001559 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001560
Jay Foad5fdd6c82011-07-12 14:06:48 +00001561 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerdf986172009-01-02 07:01:27 +00001562 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattner1afcace2011-07-09 17:41:24 +00001563 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001564
Chris Lattner1afcace2011-07-09 17:41:24 +00001565 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerdf986172009-01-02 07:01:27 +00001566 return false;
1567}
1568
Chris Lattner1afcace2011-07-09 17:41:24 +00001569/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1570/// other structs.
1571bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1572 SmallVector<Type*, 8> Elts;
1573 if (ParseStructBody(Elts)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001574
Chris Lattner1afcace2011-07-09 17:41:24 +00001575 Result = StructType::get(Context, Elts, Packed);
1576 return false;
1577}
1578
1579/// ParseStructDefinition - Parse a struct in a 'type' definition.
1580bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1581 std::pair<Type*, LocTy> &Entry,
1582 Type *&ResultTy) {
1583 // If the type was already defined, diagnose the redefinition.
1584 if (Entry.first && !Entry.second.isValid())
1585 return Error(TypeLoc, "redefinition of type");
Michael Ilseman407a6162012-11-15 22:34:00 +00001586
Chris Lattner1afcace2011-07-09 17:41:24 +00001587 // If we have opaque, just return without filling in the definition for the
1588 // struct. This counts as a definition as far as the .ll file goes.
1589 if (EatIfPresent(lltok::kw_opaque)) {
1590 // This type is being defined, so clear the location to indicate this.
1591 Entry.second = SMLoc();
Michael Ilseman407a6162012-11-15 22:34:00 +00001592
Chris Lattner1afcace2011-07-09 17:41:24 +00001593 // If this type number has never been uttered, create it.
1594 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001595 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001596 ResultTy = Entry.first;
1597 return false;
1598 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001599
Chris Lattner1afcace2011-07-09 17:41:24 +00001600 // If the type starts with '<', then it is either a packed struct or a vector.
1601 bool isPacked = EatIfPresent(lltok::less);
1602
1603 // If we don't have a struct, then we have a random type alias, which we
1604 // accept for compatibility with old files. These types are not allowed to be
1605 // forward referenced and not allowed to be recursive.
1606 if (Lex.getKind() != lltok::lbrace) {
1607 if (Entry.first)
1608 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman407a6162012-11-15 22:34:00 +00001609
Chris Lattner1afcace2011-07-09 17:41:24 +00001610 ResultTy = 0;
1611 if (isPacked)
1612 return ParseArrayVectorType(ResultTy, true);
1613 return ParseType(ResultTy);
1614 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001615
Chris Lattner1afcace2011-07-09 17:41:24 +00001616 // This type is being defined, so clear the location to indicate this.
1617 Entry.second = SMLoc();
Michael Ilseman407a6162012-11-15 22:34:00 +00001618
Chris Lattner1afcace2011-07-09 17:41:24 +00001619 // If this type number has never been uttered, create it.
1620 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001621 Entry.first = StructType::create(Context, Name);
Michael Ilseman407a6162012-11-15 22:34:00 +00001622
Chris Lattner1afcace2011-07-09 17:41:24 +00001623 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman407a6162012-11-15 22:34:00 +00001624
Chris Lattner1afcace2011-07-09 17:41:24 +00001625 SmallVector<Type*, 8> Body;
1626 if (ParseStructBody(Body) ||
1627 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1628 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001629
Chris Lattner1afcace2011-07-09 17:41:24 +00001630 STy->setBody(Body, isPacked);
1631 ResultTy = STy;
1632 return false;
1633}
1634
1635
Chris Lattnerdf986172009-01-02 07:01:27 +00001636/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattner1afcace2011-07-09 17:41:24 +00001637/// StructType
Chris Lattnerdf986172009-01-02 07:01:27 +00001638/// ::= '{' '}'
Chris Lattner1afcace2011-07-09 17:41:24 +00001639/// ::= '{' Type (',' Type)* '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00001640/// ::= '<' '{' '}' '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001641/// ::= '<' '{' Type (',' Type)* '}' '>'
1642bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001643 assert(Lex.getKind() == lltok::lbrace);
1644 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001645
Chris Lattner1afcace2011-07-09 17:41:24 +00001646 // Handle the empty struct.
1647 if (EatIfPresent(lltok::rbrace))
Chris Lattnerdf986172009-01-02 07:01:27 +00001648 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001649
Chris Lattnera9a9e072009-03-09 04:49:14 +00001650 LocTy EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001651 Type *Ty = 0;
1652 if (ParseType(Ty)) return true;
1653 Body.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001654
Chris Lattner1afcace2011-07-09 17:41:24 +00001655 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001656 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001657
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001658 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001659 EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001660 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001661
Chris Lattner1afcace2011-07-09 17:41:24 +00001662 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001663 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001664
Chris Lattner1afcace2011-07-09 17:41:24 +00001665 Body.push_back(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00001666 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001667
Chris Lattner1afcace2011-07-09 17:41:24 +00001668 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerdf986172009-01-02 07:01:27 +00001669}
1670
1671/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1672/// token has already been consumed.
Chris Lattner1afcace2011-07-09 17:41:24 +00001673/// Type
Chris Lattnerdf986172009-01-02 07:01:27 +00001674/// ::= '[' APSINTVAL 'x' Types ']'
1675/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001676bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001677 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1678 Lex.getAPSIntVal().getBitWidth() > 64)
1679 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001680
Chris Lattnerdf986172009-01-02 07:01:27 +00001681 LocTy SizeLoc = Lex.getLoc();
1682 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001683 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001684
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001685 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1686 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001687
1688 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001689 Type *EltTy = 0;
1690 if (ParseType(EltTy)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001691
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001692 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1693 "expected end of sequential type"))
1694 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001695
Chris Lattnerdf986172009-01-02 07:01:27 +00001696 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001697 if (Size == 0)
1698 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001699 if ((unsigned)Size != Size)
1700 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001701 if (!VectorType::isValidElementType(EltTy))
Duncan Sands2333e292012-11-13 12:59:33 +00001702 return Error(TypeLoc, "invalid vector element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001703 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001704 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001705 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001706 return Error(TypeLoc, "invalid array element type");
Chris Lattner1afcace2011-07-09 17:41:24 +00001707 Result = ArrayType::get(EltTy, Size);
Chris Lattnerdf986172009-01-02 07:01:27 +00001708 }
1709 return false;
1710}
1711
1712//===----------------------------------------------------------------------===//
1713// Function Semantic Analysis.
1714//===----------------------------------------------------------------------===//
1715
Chris Lattner09d9ef42009-10-28 03:39:23 +00001716LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1717 int functionNumber)
1718 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001719
1720 // Insert unnamed arguments into the NumberedVals list.
1721 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1722 AI != E; ++AI)
1723 if (!AI->hasName())
1724 NumberedVals.push_back(AI);
1725}
1726
1727LLParser::PerFunctionState::~PerFunctionState() {
1728 // If there were any forward referenced non-basicblock values, delete them.
1729 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1730 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1731 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001732 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001733 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001734 delete I->second.first;
1735 I->second.first = 0;
1736 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001737
Chris Lattnerdf986172009-01-02 07:01:27 +00001738 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1739 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1740 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001741 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001742 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001743 delete I->second.first;
1744 I->second.first = 0;
1745 }
1746}
1747
Chris Lattner09d9ef42009-10-28 03:39:23 +00001748bool LLParser::PerFunctionState::FinishFunction() {
1749 // Check to see if someone took the address of labels in this block.
1750 if (!P.ForwardRefBlockAddresses.empty()) {
1751 ValID FunctionID;
1752 if (!F.getName().empty()) {
1753 FunctionID.Kind = ValID::t_GlobalName;
1754 FunctionID.StrVal = F.getName();
1755 } else {
1756 FunctionID.Kind = ValID::t_GlobalID;
1757 FunctionID.UIntVal = FunctionNumber;
1758 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001759
Chris Lattner09d9ef42009-10-28 03:39:23 +00001760 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1761 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1762 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1763 // Resolve all these references.
1764 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1765 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001766
Chris Lattner09d9ef42009-10-28 03:39:23 +00001767 P.ForwardRefBlockAddresses.erase(FRBAI);
1768 }
1769 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001770
Chris Lattnerdf986172009-01-02 07:01:27 +00001771 if (!ForwardRefVals.empty())
1772 return P.Error(ForwardRefVals.begin()->second.second,
1773 "use of undefined value '%" + ForwardRefVals.begin()->first +
1774 "'");
1775 if (!ForwardRefValIDs.empty())
1776 return P.Error(ForwardRefValIDs.begin()->second.second,
1777 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001778 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001779 return false;
1780}
1781
1782
1783/// GetVal - Get a value with the specified name or ID, creating a
1784/// forward reference record if needed. This can return null if the value
1785/// exists but does not have the right type.
1786Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001787 Type *Ty, LocTy Loc) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001788 // Look this name up in the normal function symbol table.
1789 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001790
Chris Lattnerdf986172009-01-02 07:01:27 +00001791 // If this is a forward reference for the value, see if we already created a
1792 // forward ref record.
1793 if (Val == 0) {
1794 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1795 I = ForwardRefVals.find(Name);
1796 if (I != ForwardRefVals.end())
1797 Val = I->second.first;
1798 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001799
Chris Lattnerdf986172009-01-02 07:01:27 +00001800 // If we have the value in the symbol table or fwd-ref table, return it.
1801 if (Val) {
1802 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001803 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001804 P.Error(Loc, "'%" + Name + "' is not a basic block");
1805 else
1806 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001807 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001808 return 0;
1809 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001810
Chris Lattnerdf986172009-01-02 07:01:27 +00001811 // Don't make placeholders with invalid type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001812 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001813 P.Error(Loc, "invalid use of a non-first-class type");
1814 return 0;
1815 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001816
Chris Lattnerdf986172009-01-02 07:01:27 +00001817 // Otherwise, create a new forward reference for this value and remember it.
1818 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001819 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001820 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001821 else
1822 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001823
Chris Lattnerdf986172009-01-02 07:01:27 +00001824 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1825 return FwdVal;
1826}
1827
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001828Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +00001829 LocTy Loc) {
1830 // Look this name up in the normal function symbol table.
1831 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001832
Chris Lattnerdf986172009-01-02 07:01:27 +00001833 // If this is a forward reference for the value, see if we already created a
1834 // forward ref record.
1835 if (Val == 0) {
1836 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1837 I = ForwardRefValIDs.find(ID);
1838 if (I != ForwardRefValIDs.end())
1839 Val = I->second.first;
1840 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001841
Chris Lattnerdf986172009-01-02 07:01:27 +00001842 // If we have the value in the symbol table or fwd-ref table, return it.
1843 if (Val) {
1844 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001845 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001846 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001847 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001848 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001849 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001850 return 0;
1851 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001852
Chris Lattner1afcace2011-07-09 17:41:24 +00001853 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001854 P.Error(Loc, "invalid use of a non-first-class type");
1855 return 0;
1856 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001857
Chris Lattnerdf986172009-01-02 07:01:27 +00001858 // Otherwise, create a new forward reference for this value and remember it.
1859 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001860 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001861 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001862 else
1863 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001864
Chris Lattnerdf986172009-01-02 07:01:27 +00001865 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1866 return FwdVal;
1867}
1868
1869/// SetInstName - After an instruction is parsed and inserted into its
1870/// basic block, this installs its name.
1871bool LLParser::PerFunctionState::SetInstName(int NameID,
1872 const std::string &NameStr,
1873 LocTy NameLoc, Instruction *Inst) {
1874 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001875 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001876 if (NameID != -1 || !NameStr.empty())
1877 return P.Error(NameLoc, "instructions returning void cannot have a name");
1878 return false;
1879 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001880
Chris Lattnerdf986172009-01-02 07:01:27 +00001881 // If this was a numbered instruction, verify that the instruction is the
1882 // expected value and resolve any forward references.
1883 if (NameStr.empty()) {
1884 // If neither a name nor an ID was specified, just use the next ID.
1885 if (NameID == -1)
1886 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001887
Chris Lattnerdf986172009-01-02 07:01:27 +00001888 if (unsigned(NameID) != NumberedVals.size())
1889 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001890 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001891
Chris Lattnerdf986172009-01-02 07:01:27 +00001892 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1893 ForwardRefValIDs.find(NameID);
1894 if (FI != ForwardRefValIDs.end()) {
1895 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001896 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001897 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001898 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001899 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001900 ForwardRefValIDs.erase(FI);
1901 }
1902
1903 NumberedVals.push_back(Inst);
1904 return false;
1905 }
1906
1907 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1908 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1909 FI = ForwardRefVals.find(NameStr);
1910 if (FI != ForwardRefVals.end()) {
1911 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001912 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001913 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001914 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001915 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001916 ForwardRefVals.erase(FI);
1917 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001918
Chris Lattnerdf986172009-01-02 07:01:27 +00001919 // Set the name on the instruction.
1920 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001921
Benjamin Krameraf812352010-10-16 11:28:23 +00001922 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001923 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001924 NameStr + "'");
1925 return false;
1926}
1927
1928/// GetBB - Get a basic block with the specified name or ID, creating a
1929/// forward reference record if needed.
1930BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1931 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001932 return cast_or_null<BasicBlock>(GetVal(Name,
1933 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001934}
1935
1936BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001937 return cast_or_null<BasicBlock>(GetVal(ID,
1938 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001939}
1940
1941/// DefineBB - Define the specified basic block, which is either named or
1942/// unnamed. If there is an error, this returns null otherwise it returns
1943/// the block being defined.
1944BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1945 LocTy Loc) {
1946 BasicBlock *BB;
1947 if (Name.empty())
1948 BB = GetBB(NumberedVals.size(), Loc);
1949 else
1950 BB = GetBB(Name, Loc);
1951 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001952
Chris Lattnerdf986172009-01-02 07:01:27 +00001953 // Move the block to the end of the function. Forward ref'd blocks are
1954 // inserted wherever they happen to be referenced.
1955 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001956
Chris Lattnerdf986172009-01-02 07:01:27 +00001957 // Remove the block from forward ref sets.
1958 if (Name.empty()) {
1959 ForwardRefValIDs.erase(NumberedVals.size());
1960 NumberedVals.push_back(BB);
1961 } else {
1962 // BB forward references are already in the function symbol table.
1963 ForwardRefVals.erase(Name);
1964 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001965
Chris Lattnerdf986172009-01-02 07:01:27 +00001966 return BB;
1967}
1968
1969//===----------------------------------------------------------------------===//
1970// Constants.
1971//===----------------------------------------------------------------------===//
1972
1973/// ParseValID - Parse an abstract value that doesn't necessarily have a
1974/// type implied. For example, if we parse "4" we don't know what integer type
1975/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001976/// sanity. PFS is used to convert function-local operands of metadata (since
1977/// metadata operands are not just parsed here but also converted to values).
1978/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001979bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001980 ID.Loc = Lex.getLoc();
1981 switch (Lex.getKind()) {
1982 default: return TokError("expected value token");
1983 case lltok::GlobalID: // @42
1984 ID.UIntVal = Lex.getUIntVal();
1985 ID.Kind = ValID::t_GlobalID;
1986 break;
1987 case lltok::GlobalVar: // @foo
1988 ID.StrVal = Lex.getStrVal();
1989 ID.Kind = ValID::t_GlobalName;
1990 break;
1991 case lltok::LocalVarID: // %42
1992 ID.UIntVal = Lex.getUIntVal();
1993 ID.Kind = ValID::t_LocalID;
1994 break;
1995 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00001996 ID.StrVal = Lex.getStrVal();
1997 ID.Kind = ValID::t_LocalName;
1998 break;
Dan Gohman83448032010-07-14 18:26:50 +00001999 case lltok::exclaim: // !42, !{...}, or !"foo"
2000 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002001 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002002 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002003 ID.Kind = ValID::t_APSInt;
2004 break;
2005 case lltok::APFloat:
2006 ID.APFloatVal = Lex.getAPFloatVal();
2007 ID.Kind = ValID::t_APFloat;
2008 break;
2009 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002010 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002011 ID.Kind = ValID::t_Constant;
2012 break;
2013 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002014 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002015 ID.Kind = ValID::t_Constant;
2016 break;
2017 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2018 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2019 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002020
Chris Lattnerdf986172009-01-02 07:01:27 +00002021 case lltok::lbrace: {
2022 // ValID ::= '{' ConstVector '}'
2023 Lex.Lex();
2024 SmallVector<Constant*, 16> Elts;
2025 if (ParseGlobalValueVector(Elts) ||
2026 ParseToken(lltok::rbrace, "expected end of struct constant"))
2027 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002028
Chris Lattner1afcace2011-07-09 17:41:24 +00002029 ID.ConstantStructElts = new Constant*[Elts.size()];
2030 ID.UIntVal = Elts.size();
2031 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2032 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002033 return false;
2034 }
2035 case lltok::less: {
2036 // ValID ::= '<' ConstVector '>' --> Vector.
2037 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2038 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002039 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002040
Chris Lattnerdf986172009-01-02 07:01:27 +00002041 SmallVector<Constant*, 16> Elts;
2042 LocTy FirstEltLoc = Lex.getLoc();
2043 if (ParseGlobalValueVector(Elts) ||
2044 (isPackedStruct &&
2045 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2046 ParseToken(lltok::greater, "expected end of constant"))
2047 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002048
Chris Lattnerdf986172009-01-02 07:01:27 +00002049 if (isPackedStruct) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002050 ID.ConstantStructElts = new Constant*[Elts.size()];
2051 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2052 ID.UIntVal = Elts.size();
2053 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002054 return false;
2055 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002056
Chris Lattnerdf986172009-01-02 07:01:27 +00002057 if (Elts.empty())
2058 return Error(ID.Loc, "constant vector must not be empty");
2059
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002060 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002061 !Elts[0]->getType()->isFloatingPointTy() &&
2062 !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002063 return Error(FirstEltLoc,
Nadav Rotem16087692011-12-05 06:29:09 +00002064 "vector elements must have integer, pointer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002065
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 // Verify that all the vector elements have the same type.
2067 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2068 if (Elts[i]->getType() != Elts[0]->getType())
2069 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002070 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002071 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002072
Chris Lattner2ca5c862011-02-15 00:14:00 +00002073 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002074 ID.Kind = ValID::t_Constant;
2075 return false;
2076 }
2077 case lltok::lsquare: { // Array Constant
2078 Lex.Lex();
2079 SmallVector<Constant*, 16> Elts;
2080 LocTy FirstEltLoc = Lex.getLoc();
2081 if (ParseGlobalValueVector(Elts) ||
2082 ParseToken(lltok::rsquare, "expected end of array constant"))
2083 return true;
2084
2085 // Handle empty element.
2086 if (Elts.empty()) {
2087 // Use undef instead of an array because it's inconvenient to determine
2088 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002089 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002090 return false;
2091 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002092
Chris Lattnerdf986172009-01-02 07:01:27 +00002093 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002094 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002095 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002096
Owen Andersondebcb012009-07-29 22:17:13 +00002097 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002098
Chris Lattnerdf986172009-01-02 07:01:27 +00002099 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002100 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002101 if (Elts[i]->getType() != Elts[0]->getType())
2102 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002103 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002104 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00002105 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002106
Jay Foad26701082011-06-22 09:24:39 +00002107 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002108 ID.Kind = ValID::t_Constant;
2109 return false;
2110 }
2111 case lltok::kw_c: // c "foo"
2112 Lex.Lex();
Chris Lattner18c7f802012-02-05 02:29:43 +00002113 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2114 false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002115 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2116 ID.Kind = ValID::t_Constant;
2117 return false;
2118
2119 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002120 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
Chad Rosier581600b2012-09-05 19:00:49 +00002121 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerdf986172009-01-02 07:01:27 +00002122 Lex.Lex();
2123 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002124 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosier581600b2012-09-05 19:00:49 +00002125 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002126 ParseStringConstant(ID.StrVal) ||
2127 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002128 ParseToken(lltok::StringConstant, "expected constraint string"))
2129 return true;
2130 ID.StrVal2 = Lex.getStrVal();
Chad Rosier36547342012-09-05 00:08:17 +00002131 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosier581600b2012-09-05 19:00:49 +00002132 (unsigned(AsmDialect)<<2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002133 ID.Kind = ValID::t_InlineAsm;
2134 return false;
2135 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002136
Chris Lattner09d9ef42009-10-28 03:39:23 +00002137 case lltok::kw_blockaddress: {
2138 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2139 Lex.Lex();
2140
2141 ValID Fn, Label;
2142 LocTy FnLoc, LabelLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00002143
Chris Lattner09d9ef42009-10-28 03:39:23 +00002144 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2145 ParseValID(Fn) ||
2146 ParseToken(lltok::comma, "expected comma in block address expression")||
2147 ParseValID(Label) ||
2148 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2149 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00002150
Chris Lattner09d9ef42009-10-28 03:39:23 +00002151 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2152 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002153 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002154 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman407a6162012-11-15 22:34:00 +00002155
Chris Lattner09d9ef42009-10-28 03:39:23 +00002156 // Make a global variable as a placeholder for this reference.
2157 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2158 false, GlobalValue::InternalLinkage,
2159 0, "");
2160 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2161 ID.ConstantVal = FwdRef;
2162 ID.Kind = ValID::t_Constant;
2163 return false;
2164 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002165
Chris Lattnerdf986172009-01-02 07:01:27 +00002166 case lltok::kw_trunc:
2167 case lltok::kw_zext:
2168 case lltok::kw_sext:
2169 case lltok::kw_fptrunc:
2170 case lltok::kw_fpext:
2171 case lltok::kw_bitcast:
2172 case lltok::kw_uitofp:
2173 case lltok::kw_sitofp:
2174 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002175 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002176 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002177 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002178 unsigned Opc = Lex.getUIntVal();
Chris Lattner1afcace2011-07-09 17:41:24 +00002179 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002180 Constant *SrcVal;
2181 Lex.Lex();
2182 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2183 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002184 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002185 ParseType(DestTy) ||
2186 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2187 return true;
2188 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2189 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002190 getTypeString(SrcVal->getType()) + "' to '" +
2191 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002192 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002193 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002194 ID.Kind = ValID::t_Constant;
2195 return false;
2196 }
2197 case lltok::kw_extractvalue: {
2198 Lex.Lex();
2199 Constant *Val;
2200 SmallVector<unsigned, 4> Indices;
2201 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2202 ParseGlobalTypeAndValue(Val) ||
2203 ParseIndexList(Indices) ||
2204 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2205 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002206
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002207 if (!Val->getType()->isAggregateType())
2208 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002209 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002210 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002211 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002212 ID.Kind = ValID::t_Constant;
2213 return false;
2214 }
2215 case lltok::kw_insertvalue: {
2216 Lex.Lex();
2217 Constant *Val0, *Val1;
2218 SmallVector<unsigned, 4> Indices;
2219 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2220 ParseGlobalTypeAndValue(Val0) ||
2221 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2222 ParseGlobalTypeAndValue(Val1) ||
2223 ParseIndexList(Indices) ||
2224 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2225 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002226 if (!Val0->getType()->isAggregateType())
2227 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002228 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002229 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002230 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002231 ID.Kind = ValID::t_Constant;
2232 return false;
2233 }
2234 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002235 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002236 unsigned PredVal, Opc = Lex.getUIntVal();
2237 Constant *Val0, *Val1;
2238 Lex.Lex();
2239 if (ParseCmpPredicate(PredVal, Opc) ||
2240 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2241 ParseGlobalTypeAndValue(Val0) ||
2242 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2243 ParseGlobalTypeAndValue(Val1) ||
2244 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2245 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002246
Chris Lattnerdf986172009-01-02 07:01:27 +00002247 if (Val0->getType() != Val1->getType())
2248 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002249
Chris Lattnerdf986172009-01-02 07:01:27 +00002250 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002251
Chris Lattnerdf986172009-01-02 07:01:27 +00002252 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002253 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002254 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002255 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002256 } else {
2257 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002258 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002259 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002260 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002261 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002262 }
2263 ID.Kind = ValID::t_Constant;
2264 return false;
2265 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002266
Chris Lattnerdf986172009-01-02 07:01:27 +00002267 // Binary Operators.
2268 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002269 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002270 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002271 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002272 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002273 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002274 case lltok::kw_udiv:
2275 case lltok::kw_sdiv:
2276 case lltok::kw_fdiv:
2277 case lltok::kw_urem:
2278 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002279 case lltok::kw_frem:
2280 case lltok::kw_shl:
2281 case lltok::kw_lshr:
2282 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002283 bool NUW = false;
2284 bool NSW = false;
2285 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002286 unsigned Opc = Lex.getUIntVal();
2287 Constant *Val0, *Val1;
2288 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002289 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002290 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2291 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002292 if (EatIfPresent(lltok::kw_nuw))
2293 NUW = true;
2294 if (EatIfPresent(lltok::kw_nsw)) {
2295 NSW = true;
2296 if (EatIfPresent(lltok::kw_nuw))
2297 NUW = true;
2298 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002299 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2300 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002301 if (EatIfPresent(lltok::kw_exact))
2302 Exact = true;
2303 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002304 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2305 ParseGlobalTypeAndValue(Val0) ||
2306 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2307 ParseGlobalTypeAndValue(Val1) ||
2308 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2309 return true;
2310 if (Val0->getType() != Val1->getType())
2311 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002312 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002313 if (NUW)
2314 return Error(ModifierLoc, "nuw only applies to integer operations");
2315 if (NSW)
2316 return Error(ModifierLoc, "nsw only applies to integer operations");
2317 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002318 // Check that the type is valid for the operator.
2319 switch (Opc) {
2320 case Instruction::Add:
2321 case Instruction::Sub:
2322 case Instruction::Mul:
2323 case Instruction::UDiv:
2324 case Instruction::SDiv:
2325 case Instruction::URem:
2326 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002327 case Instruction::Shl:
2328 case Instruction::AShr:
2329 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002330 if (!Val0->getType()->isIntOrIntVectorTy())
2331 return Error(ID.Loc, "constexpr requires integer operands");
2332 break;
2333 case Instruction::FAdd:
2334 case Instruction::FSub:
2335 case Instruction::FMul:
2336 case Instruction::FDiv:
2337 case Instruction::FRem:
2338 if (!Val0->getType()->isFPOrFPVectorTy())
2339 return Error(ID.Loc, "constexpr requires fp operands");
2340 break;
2341 default: llvm_unreachable("Unknown binary operator!");
2342 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002343 unsigned Flags = 0;
2344 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2345 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002346 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002347 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002348 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002349 ID.Kind = ValID::t_Constant;
2350 return false;
2351 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002352
Chris Lattnerdf986172009-01-02 07:01:27 +00002353 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002354 case lltok::kw_and:
2355 case lltok::kw_or:
2356 case lltok::kw_xor: {
2357 unsigned Opc = Lex.getUIntVal();
2358 Constant *Val0, *Val1;
2359 Lex.Lex();
2360 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2361 ParseGlobalTypeAndValue(Val0) ||
2362 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2363 ParseGlobalTypeAndValue(Val1) ||
2364 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2365 return true;
2366 if (Val0->getType() != Val1->getType())
2367 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002368 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002369 return Error(ID.Loc,
2370 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002371 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002372 ID.Kind = ValID::t_Constant;
2373 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002374 }
2375
Chris Lattnerdf986172009-01-02 07:01:27 +00002376 case lltok::kw_getelementptr:
2377 case lltok::kw_shufflevector:
2378 case lltok::kw_insertelement:
2379 case lltok::kw_extractelement:
2380 case lltok::kw_select: {
2381 unsigned Opc = Lex.getUIntVal();
2382 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002383 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002384 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002385 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002386 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002387 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2388 ParseGlobalValueVector(Elts) ||
2389 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2390 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002391
Chris Lattnerdf986172009-01-02 07:01:27 +00002392 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem16087692011-12-05 06:29:09 +00002393 if (Elts.size() == 0 ||
2394 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002395 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002396
Jay Foaddab3d292011-07-21 14:31:17 +00002397 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foada9203102011-07-25 09:48:08 +00002398 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002399 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad4b5e2072011-07-21 15:15:37 +00002400 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2401 InBounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002402 } else if (Opc == Instruction::Select) {
2403 if (Elts.size() != 3)
2404 return Error(ID.Loc, "expected three operands to select");
2405 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2406 Elts[2]))
2407 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002408 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002409 } else if (Opc == Instruction::ShuffleVector) {
2410 if (Elts.size() != 3)
2411 return Error(ID.Loc, "expected three operands to shufflevector");
2412 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2413 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002414 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002415 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002416 } else if (Opc == Instruction::ExtractElement) {
2417 if (Elts.size() != 2)
2418 return Error(ID.Loc, "expected two operands to extractelement");
2419 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2420 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002421 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002422 } else {
2423 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2424 if (Elts.size() != 3)
2425 return Error(ID.Loc, "expected three operands to insertelement");
2426 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2427 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002428 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002429 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002430 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002431
Chris Lattnerdf986172009-01-02 07:01:27 +00002432 ID.Kind = ValID::t_Constant;
2433 return false;
2434 }
2435 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002436
Chris Lattnerdf986172009-01-02 07:01:27 +00002437 Lex.Lex();
2438 return false;
2439}
2440
2441/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002442bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez92f238d2010-01-11 22:31:58 +00002443 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002444 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002445 Value *V = NULL;
2446 bool Parsed = ParseValID(ID) ||
2447 ConvertValIDToValue(Ty, ID, V, NULL);
2448 if (V && !(C = dyn_cast<Constant>(V)))
2449 return Error(ID.Loc, "global values must be constants");
2450 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002451}
2452
Victor Hernandez92f238d2010-01-11 22:31:58 +00002453bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002454 Type *Ty = 0;
2455 return ParseType(Ty) ||
2456 ParseGlobalValue(Ty, V);
Victor Hernandez92f238d2010-01-11 22:31:58 +00002457}
2458
2459/// ParseGlobalValueVector
2460/// ::= /*empty*/
2461/// ::= TypeAndValue (',' TypeAndValue)*
2462bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2463 // Empty list.
2464 if (Lex.getKind() == lltok::rbrace ||
2465 Lex.getKind() == lltok::rsquare ||
2466 Lex.getKind() == lltok::greater ||
2467 Lex.getKind() == lltok::rparen)
2468 return false;
2469
2470 Constant *C;
2471 if (ParseGlobalTypeAndValue(C)) return true;
2472 Elts.push_back(C);
2473
2474 while (EatIfPresent(lltok::comma)) {
2475 if (ParseGlobalTypeAndValue(C)) return true;
2476 Elts.push_back(C);
2477 }
2478
2479 return false;
2480}
2481
Dan Gohman309b3af2010-08-24 02:24:03 +00002482bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2483 assert(Lex.getKind() == lltok::lbrace);
2484 Lex.Lex();
2485
2486 SmallVector<Value*, 16> Elts;
2487 if (ParseMDNodeVector(Elts, PFS) ||
2488 ParseToken(lltok::rbrace, "expected end of metadata node"))
2489 return true;
2490
Jay Foadec9186b2011-04-21 19:59:31 +00002491 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002492 ID.Kind = ValID::t_MDNode;
2493 return false;
2494}
2495
Dan Gohman83448032010-07-14 18:26:50 +00002496/// ParseMetadataValue
2497/// ::= !42
2498/// ::= !{...}
2499/// ::= !"string"
2500bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2501 assert(Lex.getKind() == lltok::exclaim);
2502 Lex.Lex();
2503
2504 // MDNode:
2505 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002506 if (Lex.getKind() == lltok::lbrace)
2507 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002508
2509 // Standalone metadata reference
2510 // !42
2511 if (Lex.getKind() == lltok::APSInt) {
2512 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2513 ID.Kind = ValID::t_MDNode;
2514 return false;
2515 }
2516
2517 // MDString:
2518 // ::= '!' STRINGCONSTANT
2519 if (ParseMDString(ID.MDStringVal)) return true;
2520 ID.Kind = ValID::t_MDString;
2521 return false;
2522}
2523
Victor Hernandez92f238d2010-01-11 22:31:58 +00002524
2525//===----------------------------------------------------------------------===//
2526// Function Parsing.
2527//===----------------------------------------------------------------------===//
2528
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002529bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez92f238d2010-01-11 22:31:58 +00002530 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002531 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002532 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002533
Chris Lattnerdf986172009-01-02 07:01:27 +00002534 switch (ID.Kind) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002535 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002536 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2537 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2538 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002539 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002540 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2541 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2542 return (V == 0);
2543 case ValID::t_InlineAsm: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002544 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman407a6162012-11-15 22:34:00 +00002545 FunctionType *FTy =
Victor Hernandez92f238d2010-01-11 22:31:58 +00002546 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2547 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2548 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosier36547342012-09-05 00:08:17 +00002549 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosier581600b2012-09-05 19:00:49 +00002550 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez92f238d2010-01-11 22:31:58 +00002551 return false;
2552 }
2553 case ValID::t_MDNode:
2554 if (!Ty->isMetadataTy())
2555 return Error(ID.Loc, "metadata value must have metadata type");
2556 V = ID.MDNodeVal;
2557 return false;
2558 case ValID::t_MDString:
2559 if (!Ty->isMetadataTy())
2560 return Error(ID.Loc, "metadata value must have metadata type");
2561 V = ID.MDStringVal;
2562 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002563 case ValID::t_GlobalName:
2564 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2565 return V == 0;
2566 case ValID::t_GlobalID:
2567 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2568 return V == 0;
2569 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002570 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002571 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002572 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002573 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002574 return false;
2575 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002576 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002577 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2578 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002579
Dan Gohmance163392011-12-17 00:04:22 +00002580 // The lexer has no type info, so builds all half, float, and double FP
2581 // constants as double. Fix this here. Long double does not need this.
2582 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002583 bool Ignored;
Dan Gohmance163392011-12-17 00:04:22 +00002584 if (Ty->isHalfTy())
2585 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2586 &Ignored);
2587 else if (Ty->isFloatTy())
2588 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2589 &Ignored);
Chris Lattnerdf986172009-01-02 07:01:27 +00002590 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002591 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002592
Chris Lattner959873d2009-01-05 18:24:23 +00002593 if (V->getType() != Ty)
2594 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002595 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002596
Chris Lattnerdf986172009-01-02 07:01:27 +00002597 return false;
2598 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002599 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002600 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002601 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002602 return false;
2603 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002604 // FIXME: LabelTy should not be a first-class type.
Chris Lattner1afcace2011-07-09 17:41:24 +00002605 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002606 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002607 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002608 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002609 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002610 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002611 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002612 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002613 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002614 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002615 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002616 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002617 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002618 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002619 return false;
2620 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002621 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002622 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002623
Chris Lattnerdf986172009-01-02 07:01:27 +00002624 V = ID.ConstantVal;
2625 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +00002626 case ValID::t_ConstantStruct:
2627 case ValID::t_PackedConstantStruct:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002628 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002629 if (ST->getNumElements() != ID.UIntVal)
2630 return Error(ID.Loc,
2631 "initializer with struct type has wrong # elements");
2632 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2633 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman407a6162012-11-15 22:34:00 +00002634
Chris Lattner1afcace2011-07-09 17:41:24 +00002635 // Verify that the elements are compatible with the structtype.
2636 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2637 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2638 return Error(ID.Loc, "element " + Twine(i) +
2639 " of struct initializer doesn't match struct element type");
Michael Ilseman407a6162012-11-15 22:34:00 +00002640
Frits van Bommel39b5abf2011-07-18 12:00:32 +00002641 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2642 ID.UIntVal));
Chris Lattner1afcace2011-07-09 17:41:24 +00002643 } else
2644 return Error(ID.Loc, "constant expression type mismatch");
2645 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002646 }
Chandler Carruth732f05c2012-01-10 18:08:01 +00002647 llvm_unreachable("Invalid ValID");
Chris Lattnerdf986172009-01-02 07:01:27 +00002648}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002649
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002650bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002651 V = 0;
2652 ValID ID;
Chris Lattner1afcace2011-07-09 17:41:24 +00002653 return ParseValID(ID, PFS) ||
2654 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002655}
2656
Chris Lattner1afcace2011-07-09 17:41:24 +00002657bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2658 Type *Ty = 0;
2659 return ParseType(Ty) ||
2660 ParseValue(Ty, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002661}
2662
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002663bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2664 PerFunctionState &PFS) {
2665 Value *V;
2666 Loc = Lex.getLoc();
2667 if (ParseTypeAndValue(V, PFS)) return true;
2668 if (!isa<BasicBlock>(V))
2669 return Error(Loc, "expected a basic block");
2670 BB = cast<BasicBlock>(V);
2671 return false;
2672}
2673
2674
Chris Lattnerdf986172009-01-02 07:01:27 +00002675/// FunctionHeader
2676/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002677/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002678/// OptionalAlign OptGC
2679bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2680 // Parse the linkage.
2681 LocTy LinkageLoc = Lex.getLoc();
2682 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002683
Kostya Serebryany164b86b2012-01-20 17:56:17 +00002684 unsigned Visibility;
Bill Wendling702cc912012-10-15 20:35:56 +00002685 AttrBuilder RetAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002686 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00002687 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002688 LocTy RetTypeLoc = Lex.getLoc();
2689 if (ParseOptionalLinkage(Linkage) ||
2690 ParseOptionalVisibility(Visibility) ||
2691 ParseOptionalCallingConv(CC) ||
2692 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002693 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002694 return true;
2695
2696 // Verify that the linkage is ok.
2697 switch ((GlobalValue::LinkageTypes)Linkage) {
2698 case GlobalValue::ExternalLinkage:
2699 break; // always ok.
2700 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002701 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002702 if (isDefine)
2703 return Error(LinkageLoc, "invalid linkage for function definition");
2704 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002705 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002706 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002707 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002708 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002709 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002710 case GlobalValue::LinkOnceAnyLinkage:
2711 case GlobalValue::LinkOnceODRLinkage:
Bill Wendling32811be2012-08-17 18:33:14 +00002712 case GlobalValue::LinkOnceODRAutoHideLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002713 case GlobalValue::WeakAnyLinkage:
2714 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002715 case GlobalValue::DLLExportLinkage:
2716 if (!isDefine)
2717 return Error(LinkageLoc, "invalid linkage for function declaration");
2718 break;
2719 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002720 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002721 return Error(LinkageLoc, "invalid function linkage type");
2722 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002723
Chris Lattner1afcace2011-07-09 17:41:24 +00002724 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002725 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002726
Chris Lattnerdf986172009-01-02 07:01:27 +00002727 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002728
2729 std::string FunctionName;
2730 if (Lex.getKind() == lltok::GlobalVar) {
2731 FunctionName = Lex.getStrVal();
2732 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2733 unsigned NameID = Lex.getUIntVal();
2734
2735 if (NameID != NumberedVals.size())
2736 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002737 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002738 } else {
2739 return TokError("expected function name");
2740 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002741
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002742 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002743
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002744 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002745 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002746
Chris Lattner1afcace2011-07-09 17:41:24 +00002747 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002748 bool isVarArg;
Bill Wendling702cc912012-10-15 20:35:56 +00002749 AttrBuilder FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002750 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002751 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002752 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002753 bool UnnamedAddr;
2754 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002755
Chris Lattner1afcace2011-07-09 17:41:24 +00002756 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002757 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2758 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002759 ParseOptionalAttrs(FuncAttrs, 2) ||
2760 (EatIfPresent(lltok::kw_section) &&
2761 ParseStringConstant(Section)) ||
2762 ParseOptionalAlignment(Alignment) ||
2763 (EatIfPresent(lltok::kw_gc) &&
2764 ParseStringConstant(GC)))
2765 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002766
2767 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingf385f4c2012-10-08 23:27:46 +00002768 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendlingef99fe82012-09-21 15:26:31 +00002769 Alignment = FuncAttrs.getAlignment();
Bill Wendlingdc4efcb2012-10-09 09:17:28 +00002770 FuncAttrs.removeAttribute(Attributes::Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00002771 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002772
Chris Lattnerdf986172009-01-02 07:01:27 +00002773 // Okay, if we got here, the function is syntactically valid. Convert types
2774 // and do semantic checks.
Jay Foad5fdd6c82011-07-12 14:06:48 +00002775 std::vector<Type*> ParamTypeList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002776 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002777
Bill Wendlinge603fe42012-09-19 23:54:18 +00002778 if (RetAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00002779 Attrs.push_back(
2780 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
2781 Attributes::get(RetType->getContext(),
2782 RetAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002783
Chris Lattnerdf986172009-01-02 07:01:27 +00002784 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002785 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlinge603fe42012-09-19 23:54:18 +00002786 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00002787 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2788 }
2789
Bill Wendlinge603fe42012-09-19 23:54:18 +00002790 if (FuncAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00002791 Attrs.push_back(
2792 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
2793 Attributes::get(RetType->getContext(),
2794 FuncAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00002795
Chris Lattnerd509d0b2012-05-28 01:47:44 +00002796 AttrListPtr PAL = AttrListPtr::get(Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002797
Bill Wendling67658342012-10-09 07:45:08 +00002798 if (PAL.getParamAttributes(1).hasAttribute(Attributes::StructRet) &&
2799 !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002800 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2801
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002802 FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002803 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002804 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002805
2806 Fn = 0;
2807 if (!FunctionName.empty()) {
2808 // If this was a definition of a forward reference, remove the definition
2809 // from the forward reference table and fill in the forward ref.
2810 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2811 ForwardRefVals.find(FunctionName);
2812 if (FRVI != ForwardRefVals.end()) {
2813 Fn = M->getFunction(FunctionName);
Nick Lewycky64ea2752012-10-11 00:38:25 +00002814 if (!Fn)
2815 return Error(FRVI->second.second, "invalid forward reference to "
2816 "function as global value!");
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002817 if (Fn->getType() != PFT)
2818 return Error(FRVI->second.second, "invalid forward reference to "
2819 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman407a6162012-11-15 22:34:00 +00002820
Chris Lattnerdf986172009-01-02 07:01:27 +00002821 ForwardRefVals.erase(FRVI);
2822 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002823 // Reject redefinitions.
2824 return Error(NameLoc, "invalid redefinition of function '" +
2825 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002826 } else if (M->getNamedValue(FunctionName)) {
2827 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002828 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002829
Dan Gohman41905542009-08-29 23:37:49 +00002830 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002831 // If this is a definition of a forward referenced function, make sure the
2832 // types agree.
2833 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2834 = ForwardRefValIDs.find(NumberedVals.size());
2835 if (I != ForwardRefValIDs.end()) {
2836 Fn = cast<Function>(I->second.first);
2837 if (Fn->getType() != PFT)
2838 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002839 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002840 ForwardRefValIDs.erase(I);
2841 }
2842 }
2843
2844 if (Fn == 0)
2845 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2846 else // Move the forward-reference to the correct spot in the module.
2847 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2848
2849 if (FunctionName.empty())
2850 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002851
Chris Lattnerdf986172009-01-02 07:01:27 +00002852 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2853 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2854 Fn->setCallingConv(CC);
2855 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002856 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002857 Fn->setAlignment(Alignment);
2858 Fn->setSection(Section);
2859 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002860
Chris Lattnerdf986172009-01-02 07:01:27 +00002861 // Add all of the arguments we parsed to the function.
2862 Function::arg_iterator ArgIt = Fn->arg_begin();
2863 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2864 // If the argument has a name, insert it into the argument symbol table.
2865 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002866
Chris Lattnerdf986172009-01-02 07:01:27 +00002867 // Set the name, if it conflicted, it will be auto-renamed.
2868 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002869
Benjamin Krameraf812352010-10-16 11:28:23 +00002870 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002871 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2872 ArgList[i].Name + "'");
2873 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002874
Chris Lattnerdf986172009-01-02 07:01:27 +00002875 return false;
2876}
2877
2878
2879/// ParseFunctionBody
2880/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002881///
2882bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002883 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002884 return TokError("expected '{' in function body");
2885 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002886
Chris Lattner09d9ef42009-10-28 03:39:23 +00002887 int FunctionNumber = -1;
2888 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman407a6162012-11-15 22:34:00 +00002889
Chris Lattner09d9ef42009-10-28 03:39:23 +00002890 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002891
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002892 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002893 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002894 return TokError("function body requires at least one basic block");
Michael Ilseman407a6162012-11-15 22:34:00 +00002895
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002896 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002897 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002898
Chris Lattnerdf986172009-01-02 07:01:27 +00002899 // Eat the }.
2900 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002901
Chris Lattnerdf986172009-01-02 07:01:27 +00002902 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002903 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002904}
2905
2906/// ParseBasicBlock
2907/// ::= LabelStr? Instruction*
2908bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2909 // If this basic block starts out with a name, remember it.
2910 std::string Name;
2911 LocTy NameLoc = Lex.getLoc();
2912 if (Lex.getKind() == lltok::LabelStr) {
2913 Name = Lex.getStrVal();
2914 Lex.Lex();
2915 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002916
Chris Lattnerdf986172009-01-02 07:01:27 +00002917 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2918 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002919
Chris Lattnerdf986172009-01-02 07:01:27 +00002920 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002921
Chris Lattnerdf986172009-01-02 07:01:27 +00002922 // Parse the instructions in this block until we get a terminator.
2923 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002924 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002925 do {
2926 // This instruction may have three possibilities for a name: a) none
2927 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2928 LocTy NameLoc = Lex.getLoc();
2929 int NameID = -1;
2930 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002931
Chris Lattnerdf986172009-01-02 07:01:27 +00002932 if (Lex.getKind() == lltok::LocalVarID) {
2933 NameID = Lex.getUIntVal();
2934 Lex.Lex();
2935 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2936 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002937 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002938 NameStr = Lex.getStrVal();
2939 Lex.Lex();
2940 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2941 return true;
2942 }
Devang Patelf633a062009-09-17 23:04:48 +00002943
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002944 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Topper85814382012-02-07 05:05:23 +00002945 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002946 case InstError: return true;
2947 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002948 BB->getInstList().push_back(Inst);
2949
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002950 // With a normal result, we check to see if the instruction is followed by
2951 // a comma and metadata.
2952 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002953 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002954 return true;
2955 break;
2956 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002957 BB->getInstList().push_back(Inst);
2958
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002959 // If the instruction parser ate an extra comma at the end of it, it
2960 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002961 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002962 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00002963 break;
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002964 }
Devang Patelf633a062009-09-17 23:04:48 +00002965
Chris Lattnerdf986172009-01-02 07:01:27 +00002966 // Set the name on the instruction.
2967 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2968 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002969
Chris Lattnerdf986172009-01-02 07:01:27 +00002970 return false;
2971}
2972
2973//===----------------------------------------------------------------------===//
2974// Instruction Parsing.
2975//===----------------------------------------------------------------------===//
2976
2977/// ParseInstruction - Parse one of the many different instructions.
2978///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002979int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2980 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002981 lltok::Kind Token = Lex.getKind();
2982 if (Token == lltok::Eof)
2983 return TokError("found end of file when expecting more instructions");
2984 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002985 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002986 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002987
Chris Lattnerdf986172009-01-02 07:01:27 +00002988 switch (Token) {
2989 default: return Error(Loc, "expected instruction opcode");
2990 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002991 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002992 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2993 case lltok::kw_br: return ParseBr(Inst, PFS);
2994 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002995 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002996 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002997 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002998 // Binary Operators.
2999 case lltok::kw_add:
3000 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00003001 case lltok::kw_mul:
3002 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00003003 bool NUW = EatIfPresent(lltok::kw_nuw);
3004 bool NSW = EatIfPresent(lltok::kw_nsw);
3005 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman407a6162012-11-15 22:34:00 +00003006
Chris Lattnerf067d582011-02-07 16:40:21 +00003007 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003008
Chris Lattnerf067d582011-02-07 16:40:21 +00003009 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3010 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3011 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00003012 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003013 case lltok::kw_fadd:
3014 case lltok::kw_fsub:
3015 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3016
Chris Lattner35bda892011-02-06 21:44:57 +00003017 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00003018 case lltok::kw_udiv:
3019 case lltok::kw_lshr:
3020 case lltok::kw_ashr: {
3021 bool Exact = EatIfPresent(lltok::kw_exact);
3022
3023 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3024 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3025 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00003026 }
3027
Chris Lattnerdf986172009-01-02 07:01:27 +00003028 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003029 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003030 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003031 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003032 case lltok::kw_and:
3033 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003034 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003035 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003036 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003037 // Casts.
3038 case lltok::kw_trunc:
3039 case lltok::kw_zext:
3040 case lltok::kw_sext:
3041 case lltok::kw_fptrunc:
3042 case lltok::kw_fpext:
3043 case lltok::kw_bitcast:
3044 case lltok::kw_uitofp:
3045 case lltok::kw_sitofp:
3046 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003047 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003048 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003049 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003050 // Other.
3051 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003052 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003053 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3054 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3055 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3056 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlinge6e88262011-08-12 20:24:12 +00003057 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003058 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3059 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3060 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003061 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003062 case lltok::kw_load: return ParseLoad(Inst, PFS);
3063 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedmanf03bb262011-08-12 22:50:01 +00003064 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3065 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedman47f35132011-07-25 23:16:38 +00003066 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003067 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3068 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3069 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3070 }
3071}
3072
3073/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3074bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003075 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003076 switch (Lex.getKind()) {
3077 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3078 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3079 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3080 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3081 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3082 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3083 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3084 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3085 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3086 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3087 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3088 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3089 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3090 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3091 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3092 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3093 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3094 }
3095 } else {
3096 switch (Lex.getKind()) {
3097 default: TokError("expected icmp predicate (e.g. 'eq')");
3098 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3099 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3100 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3101 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3102 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3103 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3104 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3105 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3106 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3107 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3108 }
3109 }
3110 Lex.Lex();
3111 return false;
3112}
3113
3114//===----------------------------------------------------------------------===//
3115// Terminator Instructions.
3116//===----------------------------------------------------------------------===//
3117
3118/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003119/// ::= 'ret' void (',' !dbg, !1)*
3120/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003121bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattner1afcace2011-07-09 17:41:24 +00003122 PerFunctionState &PFS) {
3123 SMLoc TypeLoc = Lex.getLoc();
3124 Type *Ty = 0;
Chris Lattnera9a9e072009-03-09 04:49:14 +00003125 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003126
Chris Lattner1afcace2011-07-09 17:41:24 +00003127 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman407a6162012-11-15 22:34:00 +00003128
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003129 if (Ty->isVoidTy()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003130 if (!ResType->isVoidTy())
3131 return Error(TypeLoc, "value doesn't match function result type '" +
3132 getTypeString(ResType) + "'");
Michael Ilseman407a6162012-11-15 22:34:00 +00003133
Owen Anderson1d0be152009-08-13 21:58:54 +00003134 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003135 return false;
3136 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003137
Chris Lattnerdf986172009-01-02 07:01:27 +00003138 Value *RV;
3139 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003140
Chris Lattner1afcace2011-07-09 17:41:24 +00003141 if (ResType != RV->getType())
3142 return Error(TypeLoc, "value doesn't match function result type '" +
3143 getTypeString(ResType) + "'");
Michael Ilseman407a6162012-11-15 22:34:00 +00003144
Owen Anderson1d0be152009-08-13 21:58:54 +00003145 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003146 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003147}
3148
3149
3150/// ParseBr
3151/// ::= 'br' TypeAndValue
3152/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3153bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3154 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003155 Value *Op0;
3156 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003157 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003158
Chris Lattnerdf986172009-01-02 07:01:27 +00003159 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3160 Inst = BranchInst::Create(BB);
3161 return false;
3162 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003163
Owen Anderson1d0be152009-08-13 21:58:54 +00003164 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003165 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003166
Chris Lattnerdf986172009-01-02 07:01:27 +00003167 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003168 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003169 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003170 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003171 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003172
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003173 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003174 return false;
3175}
3176
3177/// ParseSwitch
3178/// Instruction
3179/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3180/// JumpTable
3181/// ::= (TypeAndValue ',' TypeAndValue)*
3182bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3183 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003184 Value *Cond;
3185 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003186 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3187 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003188 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003189 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3190 return true;
3191
Duncan Sands1df98592010-02-16 11:11:14 +00003192 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003193 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003194
Chris Lattnerdf986172009-01-02 07:01:27 +00003195 // Parse the jump table pairs.
3196 SmallPtrSet<Value*, 32> SeenCases;
3197 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3198 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003199 Value *Constant;
3200 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003201
Chris Lattnerdf986172009-01-02 07:01:27 +00003202 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3203 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003204 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003205 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003206
Chris Lattnerdf986172009-01-02 07:01:27 +00003207 if (!SeenCases.insert(Constant))
3208 return Error(CondLoc, "duplicate case value in switch");
3209 if (!isa<ConstantInt>(Constant))
3210 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003211
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003212 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003213 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003214
Chris Lattnerdf986172009-01-02 07:01:27 +00003215 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003216
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003217 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003218 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3219 SI->addCase(Table[i].first, Table[i].second);
3220 Inst = SI;
3221 return false;
3222}
3223
Chris Lattnerab21db72009-10-28 00:19:10 +00003224/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003225/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003226/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3227bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003228 LocTy AddrLoc;
3229 Value *Address;
3230 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003231 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3232 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003233 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003234
Duncan Sands1df98592010-02-16 11:11:14 +00003235 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003236 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman407a6162012-11-15 22:34:00 +00003237
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003238 // Parse the destination list.
3239 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman407a6162012-11-15 22:34:00 +00003240
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003241 if (Lex.getKind() != lltok::rsquare) {
3242 BasicBlock *DestBB;
3243 if (ParseTypeAndBasicBlock(DestBB, PFS))
3244 return true;
3245 DestList.push_back(DestBB);
Michael Ilseman407a6162012-11-15 22:34:00 +00003246
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003247 while (EatIfPresent(lltok::comma)) {
3248 if (ParseTypeAndBasicBlock(DestBB, PFS))
3249 return true;
3250 DestList.push_back(DestBB);
3251 }
3252 }
Michael Ilseman407a6162012-11-15 22:34:00 +00003253
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003254 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3255 return true;
3256
Chris Lattnerab21db72009-10-28 00:19:10 +00003257 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003258 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3259 IBI->addDestination(DestList[i]);
3260 Inst = IBI;
3261 return false;
3262}
3263
3264
Chris Lattnerdf986172009-01-02 07:01:27 +00003265/// ParseInvoke
3266/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3267/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3268bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3269 LocTy CallLoc = Lex.getLoc();
Bill Wendling702cc912012-10-15 20:35:56 +00003270 AttrBuilder RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003271 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003272 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003273 LocTy RetTypeLoc;
3274 ValID CalleeID;
3275 SmallVector<ParamInfo, 16> ArgList;
3276
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003277 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003278 if (ParseOptionalCallingConv(CC) ||
3279 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003280 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003281 ParseValID(CalleeID) ||
3282 ParseParameterList(ArgList, PFS) ||
3283 ParseOptionalAttrs(FnAttrs, 2) ||
3284 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003285 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003286 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003287 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003288 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003289
Chris Lattnerdf986172009-01-02 07:01:27 +00003290 // If RetType is a non-function pointer type, then this is the short syntax
3291 // for the call, which means that RetType is just the return type. Infer the
3292 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003293 PointerType *PFTy = 0;
3294 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003295 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3296 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3297 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003298 std::vector<Type*> ParamTypes;
Chris Lattnerdf986172009-01-02 07:01:27 +00003299 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3300 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003301
Chris Lattnerdf986172009-01-02 07:01:27 +00003302 if (!FunctionType::isValidReturnType(RetType))
3303 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003304
Owen Andersondebcb012009-07-29 22:17:13 +00003305 Ty = FunctionType::get(RetType, ParamTypes, false);
3306 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003307 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003308
Chris Lattnerdf986172009-01-02 07:01:27 +00003309 // Look up the callee.
3310 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003311 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003312
Chris Lattnerdf986172009-01-02 07:01:27 +00003313 // Set up the Attributes for the function.
3314 SmallVector<AttributeWithIndex, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003315 if (RetAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003316 Attrs.push_back(
3317 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
3318 Attributes::get(Callee->getContext(),
3319 RetAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003320
Chris Lattnerdf986172009-01-02 07:01:27 +00003321 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003322
Chris Lattnerdf986172009-01-02 07:01:27 +00003323 // Loop through FunctionType's arguments and ensure they are specified
3324 // correctly. Also, gather any parameter attributes.
3325 FunctionType::param_iterator I = Ty->param_begin();
3326 FunctionType::param_iterator E = Ty->param_end();
3327 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003328 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003329 if (I != E) {
3330 ExpectedTy = *I++;
3331 } else if (!Ty->isVarArg()) {
3332 return Error(ArgList[i].Loc, "too many arguments specified");
3333 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003334
Chris Lattnerdf986172009-01-02 07:01:27 +00003335 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3336 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003337 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003338 Args.push_back(ArgList[i].V);
Bill Wendlinge603fe42012-09-19 23:54:18 +00003339 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003340 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3341 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003342
Chris Lattnerdf986172009-01-02 07:01:27 +00003343 if (I != E)
3344 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003345
Bill Wendlinge603fe42012-09-19 23:54:18 +00003346 if (FnAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003347 Attrs.push_back(
3348 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
3349 Attributes::get(Callee->getContext(),
3350 FnAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003351
Chris Lattnerdf986172009-01-02 07:01:27 +00003352 // Finish off the Attributes and check them
Chris Lattnerd509d0b2012-05-28 01:47:44 +00003353 AttrListPtr PAL = AttrListPtr::get(Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003354
Jay Foada3efbb12011-07-15 08:37:34 +00003355 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003356 II->setCallingConv(CC);
3357 II->setAttributes(PAL);
3358 Inst = II;
3359 return false;
3360}
3361
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003362/// ParseResume
3363/// ::= 'resume' TypeAndValue
3364bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3365 Value *Exn; LocTy ExnLoc;
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003366 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3367 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003368
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003369 ResumeInst *RI = ResumeInst::Create(Exn);
3370 Inst = RI;
3371 return false;
3372}
Chris Lattnerdf986172009-01-02 07:01:27 +00003373
3374//===----------------------------------------------------------------------===//
3375// Binary Operators.
3376//===----------------------------------------------------------------------===//
3377
3378/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003379/// ::= ArithmeticOps TypeAndValue ',' Value
3380///
3381/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3382/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003383bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003384 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003385 LocTy Loc; Value *LHS, *RHS;
3386 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3387 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3388 ParseValue(LHS->getType(), RHS, PFS))
3389 return true;
3390
Chris Lattnere914b592009-01-05 08:24:46 +00003391 bool Valid;
3392 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003393 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003394 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003395 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3396 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003397 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003398 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3399 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003400 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003401
Chris Lattnere914b592009-01-05 08:24:46 +00003402 if (!Valid)
3403 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003404
Chris Lattnerdf986172009-01-02 07:01:27 +00003405 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3406 return false;
3407}
3408
3409/// ParseLogical
3410/// ::= ArithmeticOps TypeAndValue ',' Value {
3411bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3412 unsigned Opc) {
3413 LocTy Loc; Value *LHS, *RHS;
3414 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3415 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3416 ParseValue(LHS->getType(), RHS, PFS))
3417 return true;
3418
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003419 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003420 return Error(Loc,"instruction requires integer or integer vector operands");
3421
3422 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3423 return false;
3424}
3425
3426
3427/// ParseCompare
3428/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3429/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003430bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3431 unsigned Opc) {
3432 // Parse the integer/fp comparison predicate.
3433 LocTy Loc;
3434 unsigned Pred;
3435 Value *LHS, *RHS;
3436 if (ParseCmpPredicate(Pred, Opc) ||
3437 ParseTypeAndValue(LHS, Loc, PFS) ||
3438 ParseToken(lltok::comma, "expected ',' after compare value") ||
3439 ParseValue(LHS->getType(), RHS, PFS))
3440 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003441
Chris Lattnerdf986172009-01-02 07:01:27 +00003442 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003443 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003444 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003445 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003446 } else {
3447 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003448 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00003449 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003450 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003451 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003452 }
3453 return false;
3454}
3455
3456//===----------------------------------------------------------------------===//
3457// Other Instructions.
3458//===----------------------------------------------------------------------===//
3459
3460
3461/// ParseCast
3462/// ::= CastOpc TypeAndValue 'to' Type
3463bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3464 unsigned Opc) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003465 LocTy Loc;
3466 Value *Op;
3467 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003468 if (ParseTypeAndValue(Op, Loc, PFS) ||
3469 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3470 ParseType(DestTy))
3471 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003472
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003473 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3474 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003475 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003476 getTypeString(Op->getType()) + "' to '" +
3477 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003478 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003479 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3480 return false;
3481}
3482
3483/// ParseSelect
3484/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3485bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3486 LocTy Loc;
3487 Value *Op0, *Op1, *Op2;
3488 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3489 ParseToken(lltok::comma, "expected ',' after select condition") ||
3490 ParseTypeAndValue(Op1, PFS) ||
3491 ParseToken(lltok::comma, "expected ',' after select value") ||
3492 ParseTypeAndValue(Op2, PFS))
3493 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003494
Chris Lattnerdf986172009-01-02 07:01:27 +00003495 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3496 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003497
Chris Lattnerdf986172009-01-02 07:01:27 +00003498 Inst = SelectInst::Create(Op0, Op1, Op2);
3499 return false;
3500}
3501
Chris Lattner0088a5c2009-01-05 08:18:44 +00003502/// ParseVA_Arg
3503/// ::= 'va_arg' TypeAndValue ',' Type
3504bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003505 Value *Op;
Chris Lattner1afcace2011-07-09 17:41:24 +00003506 Type *EltTy = 0;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003507 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003508 if (ParseTypeAndValue(Op, PFS) ||
3509 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003510 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003511 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003512
Chris Lattner0088a5c2009-01-05 08:18:44 +00003513 if (!EltTy->isFirstClassType())
3514 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003515
3516 Inst = new VAArgInst(Op, EltTy);
3517 return false;
3518}
3519
3520/// ParseExtractElement
3521/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3522bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3523 LocTy Loc;
3524 Value *Op0, *Op1;
3525 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3526 ParseToken(lltok::comma, "expected ',' after extract value") ||
3527 ParseTypeAndValue(Op1, PFS))
3528 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003529
Chris Lattnerdf986172009-01-02 07:01:27 +00003530 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3531 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003532
Eric Christophera3500da2009-07-25 02:28:41 +00003533 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003534 return false;
3535}
3536
3537/// ParseInsertElement
3538/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3539bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3540 LocTy Loc;
3541 Value *Op0, *Op1, *Op2;
3542 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3543 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3544 ParseTypeAndValue(Op1, PFS) ||
3545 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3546 ParseTypeAndValue(Op2, PFS))
3547 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003548
Chris Lattnerdf986172009-01-02 07:01:27 +00003549 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003550 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003551
Chris Lattnerdf986172009-01-02 07:01:27 +00003552 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3553 return false;
3554}
3555
3556/// ParseShuffleVector
3557/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3558bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3559 LocTy Loc;
3560 Value *Op0, *Op1, *Op2;
3561 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3562 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3563 ParseTypeAndValue(Op1, PFS) ||
3564 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3565 ParseTypeAndValue(Op2, PFS))
3566 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003567
Chris Lattnerdf986172009-01-02 07:01:27 +00003568 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperaf393682012-02-01 23:43:12 +00003569 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003570
Chris Lattnerdf986172009-01-02 07:01:27 +00003571 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3572 return false;
3573}
3574
3575/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003576/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003577int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003578 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003579 Value *Op0, *Op1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003580
Chris Lattner1afcace2011-07-09 17:41:24 +00003581 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003582 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3583 ParseValue(Ty, Op0, PFS) ||
3584 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003585 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003586 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3587 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003588
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003589 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003590 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3591 while (1) {
3592 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003593
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003594 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003595 break;
3596
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003597 if (Lex.getKind() == lltok::MetadataVar) {
3598 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003599 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003600 }
Devang Patela43d46f2009-10-16 18:45:49 +00003601
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003602 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003603 ParseValue(Ty, Op0, PFS) ||
3604 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003605 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003606 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3607 return true;
3608 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003609
Chris Lattnerdf986172009-01-02 07:01:27 +00003610 if (!Ty->isFirstClassType())
3611 return Error(TypeLoc, "phi node must have first class type");
3612
Jay Foad3ecfc862011-03-30 11:28:46 +00003613 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003614 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3615 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3616 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003617 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003618}
3619
Bill Wendlinge6e88262011-08-12 20:24:12 +00003620/// ParseLandingPad
3621/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3622/// Clause
3623/// ::= 'catch' TypeAndValue
3624/// ::= 'filter'
3625/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3626bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3627 Type *Ty = 0; LocTy TyLoc;
3628 Value *PersFn; LocTy PersFnLoc;
Bill Wendlinge6e88262011-08-12 20:24:12 +00003629
3630 if (ParseType(Ty, TyLoc) ||
3631 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3632 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3633 return true;
3634
3635 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3636 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3637
3638 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3639 LandingPadInst::ClauseType CT;
3640 if (EatIfPresent(lltok::kw_catch))
3641 CT = LandingPadInst::Catch;
3642 else if (EatIfPresent(lltok::kw_filter))
3643 CT = LandingPadInst::Filter;
3644 else
3645 return TokError("expected 'catch' or 'filter' clause type");
3646
3647 Value *V; LocTy VLoc;
3648 if (ParseTypeAndValue(V, VLoc, PFS)) {
3649 delete LP;
3650 return true;
3651 }
3652
Bill Wendling746c8822011-08-12 20:52:25 +00003653 // A 'catch' type expects a non-array constant. A filter clause expects an
3654 // array constant.
3655 if (CT == LandingPadInst::Catch) {
3656 if (isa<ArrayType>(V->getType()))
3657 Error(VLoc, "'catch' clause has an invalid type");
3658 } else {
3659 if (!isa<ArrayType>(V->getType()))
3660 Error(VLoc, "'filter' clause has an invalid type");
3661 }
3662
Bill Wendlinge6e88262011-08-12 20:24:12 +00003663 LP->addClause(V);
3664 }
3665
3666 Inst = LP;
3667 return false;
3668}
3669
Chris Lattnerdf986172009-01-02 07:01:27 +00003670/// ParseCall
3671/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3672/// ParameterList OptionalAttrs
3673bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3674 bool isTail) {
Bill Wendling702cc912012-10-15 20:35:56 +00003675 AttrBuilder RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003676 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003677 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003678 LocTy RetTypeLoc;
3679 ValID CalleeID;
3680 SmallVector<ParamInfo, 16> ArgList;
3681 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003682
Chris Lattnerdf986172009-01-02 07:01:27 +00003683 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3684 ParseOptionalCallingConv(CC) ||
3685 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003686 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003687 ParseValID(CalleeID) ||
3688 ParseParameterList(ArgList, PFS) ||
3689 ParseOptionalAttrs(FnAttrs, 2))
3690 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003691
Chris Lattnerdf986172009-01-02 07:01:27 +00003692 // If RetType is a non-function pointer type, then this is the short syntax
3693 // for the call, which means that RetType is just the return type. Infer the
3694 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003695 PointerType *PFTy = 0;
3696 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003697 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3698 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3699 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003700 std::vector<Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003701 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3702 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003703
Chris Lattnerdf986172009-01-02 07:01:27 +00003704 if (!FunctionType::isValidReturnType(RetType))
3705 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003706
Owen Andersondebcb012009-07-29 22:17:13 +00003707 Ty = FunctionType::get(RetType, ParamTypes, false);
3708 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003709 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003710
Chris Lattnerdf986172009-01-02 07:01:27 +00003711 // Look up the callee.
3712 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003713 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003714
Chris Lattnerdf986172009-01-02 07:01:27 +00003715 // Set up the Attributes for the function.
3716 SmallVector<AttributeWithIndex, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003717 if (RetAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003718 Attrs.push_back(
3719 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
3720 Attributes::get(Callee->getContext(),
3721 RetAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003722
Chris Lattnerdf986172009-01-02 07:01:27 +00003723 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003724
Chris Lattnerdf986172009-01-02 07:01:27 +00003725 // Loop through FunctionType's arguments and ensure they are specified
3726 // correctly. Also, gather any parameter attributes.
3727 FunctionType::param_iterator I = Ty->param_begin();
3728 FunctionType::param_iterator E = Ty->param_end();
3729 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003730 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003731 if (I != E) {
3732 ExpectedTy = *I++;
3733 } else if (!Ty->isVarArg()) {
3734 return Error(ArgList[i].Loc, "too many arguments specified");
3735 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003736
Chris Lattnerdf986172009-01-02 07:01:27 +00003737 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3738 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003739 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003740 Args.push_back(ArgList[i].V);
Bill Wendlinge603fe42012-09-19 23:54:18 +00003741 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003742 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3743 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003744
Chris Lattnerdf986172009-01-02 07:01:27 +00003745 if (I != E)
3746 return Error(CallLoc, "not enough parameters specified for call");
3747
Bill Wendlinge603fe42012-09-19 23:54:18 +00003748 if (FnAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003749 Attrs.push_back(
3750 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
3751 Attributes::get(Callee->getContext(),
3752 FnAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00003753
3754 // Finish off the Attributes and check them
Chris Lattnerd509d0b2012-05-28 01:47:44 +00003755 AttrListPtr PAL = AttrListPtr::get(Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003756
Jay Foada3efbb12011-07-15 08:37:34 +00003757 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003758 CI->setTailCall(isTail);
3759 CI->setCallingConv(CC);
3760 CI->setAttributes(PAL);
3761 Inst = CI;
3762 return false;
3763}
3764
3765//===----------------------------------------------------------------------===//
3766// Memory Instructions.
3767//===----------------------------------------------------------------------===//
3768
3769/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003770/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003771int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003772 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003773 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003774 unsigned Alignment = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00003775 Type *Ty = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003776 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003777
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003778 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003779 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003780 if (Lex.getKind() == lltok::kw_align) {
3781 if (ParseOptionalAlignment(Alignment)) return true;
3782 } else if (Lex.getKind() == lltok::MetadataVar) {
3783 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003784 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003785 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3786 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3787 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003788 }
3789 }
3790
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003791 if (Size && !Size->getType()->isIntegerTy())
3792 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003793
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003794 Inst = new AllocaInst(Ty, Size, Alignment);
3795 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003796}
3797
3798/// ParseLoad
Eli Friedmanf03bb262011-08-12 22:50:01 +00003799/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman407a6162012-11-15 22:34:00 +00003800/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedmanf03bb262011-08-12 22:50:01 +00003801/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003802int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003803 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003804 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003805 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003806 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003807 AtomicOrdering Ordering = NotAtomic;
3808 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003809
3810 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003811 isAtomic = true;
3812 Lex.Lex();
3813 }
3814
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003815 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003816 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003817 isVolatile = true;
3818 Lex.Lex();
3819 }
3820
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003821 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003822 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003823 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3824 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003825
Duncan Sands1df98592010-02-16 11:11:14 +00003826 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003827 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3828 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman21006d42011-08-09 23:02:53 +00003829 if (isAtomic && !Alignment)
3830 return Error(Loc, "atomic load must have explicit non-zero alignment");
3831 if (Ordering == Release || Ordering == AcquireRelease)
3832 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003833
Eli Friedman21006d42011-08-09 23:02:53 +00003834 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003835 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003836}
3837
3838/// ParseStore
Eli Friedmanf03bb262011-08-12 22:50:01 +00003839
3840/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3841/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman21006d42011-08-09 23:02:53 +00003842/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003843int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003844 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003845 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003846 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003847 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003848 AtomicOrdering Ordering = NotAtomic;
3849 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003850
3851 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003852 isAtomic = true;
3853 Lex.Lex();
3854 }
3855
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003856 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003857 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003858 isVolatile = true;
3859 Lex.Lex();
3860 }
3861
Chris Lattnerdf986172009-01-02 07:01:27 +00003862 if (ParseTypeAndValue(Val, Loc, PFS) ||
3863 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003864 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003865 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003866 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003867 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003868
Duncan Sands1df98592010-02-16 11:11:14 +00003869 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003870 return Error(PtrLoc, "store operand must be a pointer");
3871 if (!Val->getType()->isFirstClassType())
3872 return Error(Loc, "store operand must be a first class value");
3873 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3874 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman21006d42011-08-09 23:02:53 +00003875 if (isAtomic && !Alignment)
3876 return Error(Loc, "atomic store must have explicit non-zero alignment");
3877 if (Ordering == Acquire || Ordering == AcquireRelease)
3878 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003879
Eli Friedman21006d42011-08-09 23:02:53 +00003880 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003881 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003882}
3883
Eli Friedmanff030482011-07-28 21:48:00 +00003884/// ParseCmpXchg
Eli Friedmanf03bb262011-08-12 22:50:01 +00003885/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3886/// 'singlethread'? AtomicOrdering
3887int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003888 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3889 bool AteExtraComma = false;
3890 AtomicOrdering Ordering = NotAtomic;
3891 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003892 bool isVolatile = false;
3893
3894 if (EatIfPresent(lltok::kw_volatile))
3895 isVolatile = true;
3896
Eli Friedmanff030482011-07-28 21:48:00 +00003897 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3898 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3899 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3900 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3901 ParseTypeAndValue(New, NewLoc, PFS) ||
3902 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3903 return true;
3904
3905 if (Ordering == Unordered)
3906 return TokError("cmpxchg cannot be unordered");
3907 if (!Ptr->getType()->isPointerTy())
3908 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3909 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3910 return Error(CmpLoc, "compare value and pointer type do not match");
3911 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3912 return Error(NewLoc, "new value and pointer type do not match");
3913 if (!New->getType()->isIntegerTy())
3914 return Error(NewLoc, "cmpxchg operand must be an integer");
3915 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3916 if (Size < 8 || (Size & (Size - 1)))
3917 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3918 " integer");
3919
3920 AtomicCmpXchgInst *CXI =
3921 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3922 CXI->setVolatile(isVolatile);
3923 Inst = CXI;
3924 return AteExtraComma ? InstExtraComma : InstNormal;
3925}
3926
3927/// ParseAtomicRMW
Eli Friedmanf03bb262011-08-12 22:50:01 +00003928/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3929/// 'singlethread'? AtomicOrdering
3930int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003931 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3932 bool AteExtraComma = false;
3933 AtomicOrdering Ordering = NotAtomic;
3934 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003935 bool isVolatile = false;
Eli Friedmanff030482011-07-28 21:48:00 +00003936 AtomicRMWInst::BinOp Operation;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003937
3938 if (EatIfPresent(lltok::kw_volatile))
3939 isVolatile = true;
3940
Eli Friedmanff030482011-07-28 21:48:00 +00003941 switch (Lex.getKind()) {
3942 default: return TokError("expected binary operation in atomicrmw");
3943 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3944 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3945 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3946 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3947 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3948 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3949 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3950 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3951 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3952 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3953 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3954 }
3955 Lex.Lex(); // Eat the operation.
3956
3957 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3958 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3959 ParseTypeAndValue(Val, ValLoc, PFS) ||
3960 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3961 return true;
3962
3963 if (Ordering == Unordered)
3964 return TokError("atomicrmw cannot be unordered");
3965 if (!Ptr->getType()->isPointerTy())
3966 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3967 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3968 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3969 if (!Val->getType()->isIntegerTy())
3970 return Error(ValLoc, "atomicrmw operand must be an integer");
3971 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3972 if (Size < 8 || (Size & (Size - 1)))
3973 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3974 " integer");
3975
3976 AtomicRMWInst *RMWI =
3977 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3978 RMWI->setVolatile(isVolatile);
3979 Inst = RMWI;
3980 return AteExtraComma ? InstExtraComma : InstNormal;
3981}
3982
Eli Friedman47f35132011-07-25 23:16:38 +00003983/// ParseFence
3984/// ::= 'fence' 'singlethread'? AtomicOrdering
3985int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3986 AtomicOrdering Ordering = NotAtomic;
3987 SynchronizationScope Scope = CrossThread;
3988 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3989 return true;
3990
3991 if (Ordering == Unordered)
3992 return TokError("fence cannot be unordered");
3993 if (Ordering == Monotonic)
3994 return TokError("fence cannot be monotonic");
3995
3996 Inst = new FenceInst(Context, Ordering, Scope);
3997 return InstNormal;
3998}
3999
Chris Lattnerdf986172009-01-02 07:01:27 +00004000/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00004001/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004002int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Nadav Rotem16087692011-12-05 06:29:09 +00004003 Value *Ptr = 0;
4004 Value *Val = 0;
4005 LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00004006
Dan Gohmandcb40a32009-07-29 15:58:36 +00004007 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00004008
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004009 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00004010
Nadav Rotem16087692011-12-05 06:29:09 +00004011 if (!Ptr->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00004012 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004013
Chris Lattnerdf986172009-01-02 07:01:27 +00004014 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004015 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004016 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004017 if (Lex.getKind() == lltok::MetadataVar) {
4018 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00004019 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004020 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004021 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem16087692011-12-05 06:29:09 +00004022 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00004023 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem16087692011-12-05 06:29:09 +00004024 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4025 return Error(EltLoc, "getelementptr index type missmatch");
4026 if (Val->getType()->isVectorTy()) {
4027 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4028 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4029 if (ValNumEl != PtrNumEl)
4030 return Error(EltLoc,
4031 "getelementptr vector index has a wrong number of elements");
4032 }
Chris Lattnerdf986172009-01-02 07:01:27 +00004033 Indices.push_back(Val);
4034 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00004035
Jay Foada9203102011-07-25 09:48:08 +00004036 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004037 return Error(Loc, "invalid getelementptr indices");
Jay Foada9203102011-07-25 09:48:08 +00004038 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohmandd8004d2009-07-27 21:53:46 +00004039 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004040 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004041 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004042}
4043
4044/// ParseExtractValue
4045/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004046int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004047 Value *Val; LocTy Loc;
4048 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004049 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004050 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004051 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004052 return true;
4053
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004054 if (!Val->getType()->isAggregateType())
4055 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00004056
Jay Foadfc6d3a42011-07-13 10:26:04 +00004057 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004058 return Error(Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004059 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004060 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004061}
4062
4063/// ParseInsertValue
4064/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004065int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004066 Value *Val0, *Val1; LocTy Loc0, Loc1;
4067 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004068 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004069 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4070 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4071 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004072 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004073 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00004074
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004075 if (!Val0->getType()->isAggregateType())
4076 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004077
Jay Foadfc6d3a42011-07-13 10:26:04 +00004078 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004079 return Error(Loc0, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004080 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004081 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004082}
Nick Lewycky21cc4462009-04-04 07:22:01 +00004083
4084//===----------------------------------------------------------------------===//
4085// Embedded metadata.
4086//===----------------------------------------------------------------------===//
4087
4088/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00004089/// ::= Element (',' Element)*
4090/// Element
4091/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00004092bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00004093 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00004094 // Check for an empty list.
4095 if (Lex.getKind() == lltok::rbrace)
4096 return false;
4097
Nick Lewycky21cc4462009-04-04 07:22:01 +00004098 do {
Chris Lattnera7352392009-12-30 04:42:57 +00004099 // Null is a special case since it is typeless.
4100 if (EatIfPresent(lltok::kw_null)) {
4101 Elts.push_back(0);
4102 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00004103 }
Michael Ilseman407a6162012-11-15 22:34:00 +00004104
Chris Lattnera7352392009-12-30 04:42:57 +00004105 Value *V = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00004106 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00004107 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004108 } while (EatIfPresent(lltok::comma));
4109
4110 return false;
4111}