blob: 8a9f951908c92eadb9050af68d26e4eb0591d4eb [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;
Dan Gohman3845e502009-08-12 23:32:33 +0000171 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000172 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000173 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000174 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000175 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000176 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000177
178 // The Global variable production with no name can have many different
179 // optional leading prefixes, the production is:
180 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000181 // OptionalAddrSpace OptionalUnNammedAddr
182 // ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000183 case lltok::kw_private: // OptionalLinkage
184 case lltok::kw_linker_private: // OptionalLinkage
185 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling32811be2012-08-17 18:33:14 +0000186 case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat.
Bill Wendling5e721d72010-07-01 21:55:59 +0000187 case lltok::kw_internal: // OptionalLinkage
188 case lltok::kw_weak: // OptionalLinkage
189 case lltok::kw_weak_odr: // OptionalLinkage
190 case lltok::kw_linkonce: // OptionalLinkage
191 case lltok::kw_linkonce_odr: // OptionalLinkage
Bill Wendling32811be2012-08-17 18:33:14 +0000192 case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000193 case lltok::kw_appending: // OptionalLinkage
194 case lltok::kw_dllexport: // OptionalLinkage
195 case lltok::kw_common: // OptionalLinkage
196 case lltok::kw_dllimport: // OptionalLinkage
197 case lltok::kw_extern_weak: // OptionalLinkage
198 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000199 unsigned Linkage, Visibility;
200 if (ParseOptionalLinkage(Linkage) ||
201 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000202 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000203 return true;
204 break;
205 }
206 case lltok::kw_default: // OptionalVisibility
207 case lltok::kw_hidden: // OptionalVisibility
208 case lltok::kw_protected: { // OptionalVisibility
209 unsigned Visibility;
210 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000211 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000212 return true;
213 break;
214 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000215
Chris Lattnerdf986172009-01-02 07:01:27 +0000216 case lltok::kw_thread_local: // OptionalThreadLocal
217 case lltok::kw_addrspace: // OptionalAddrSpace
218 case lltok::kw_constant: // GlobalType
219 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000220 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000221 break;
222 }
223 }
224}
225
226
227/// toplevelentity
228/// ::= 'module' 'asm' STRINGCONSTANT
229bool LLParser::ParseModuleAsm() {
230 assert(Lex.getKind() == lltok::kw_module);
231 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000232
233 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000234 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
235 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000236
Rafael Espindola38c4e532011-03-02 04:14:42 +0000237 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000238 return false;
239}
240
241/// toplevelentity
242/// ::= 'target' 'triple' '=' STRINGCONSTANT
243/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
244bool LLParser::ParseTargetDefinition() {
245 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000246 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000247 switch (Lex.Lex()) {
248 default: return TokError("unknown target property");
249 case lltok::kw_triple:
250 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000251 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
252 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000253 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000254 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000255 return false;
256 case lltok::kw_datalayout:
257 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000258 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
259 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000260 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000261 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000262 return false;
263 }
264}
265
Dan Gohman3845e502009-08-12 23:32:33 +0000266/// ParseUnnamedType:
Dan Gohman3845e502009-08-12 23:32:33 +0000267/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000268bool LLParser::ParseUnnamedType() {
Chris Lattneredcaca82011-06-18 23:51:31 +0000269 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +0000270 unsigned TypeID = Lex.getUIntVal();
Chris Lattnera53616d2011-06-19 00:03:46 +0000271 Lex.Lex(); // eat LocalVarID;
272
273 if (ParseToken(lltok::equal, "expected '=' after name") ||
274 ParseToken(lltok::kw_type, "expected 'type' after '='"))
275 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000276
Chris Lattner1afcace2011-07-09 17:41:24 +0000277 if (TypeID >= NumberedTypes.size())
278 NumberedTypes.resize(TypeID+1);
Michael Ilseman407a6162012-11-15 22:34:00 +0000279
Chris Lattner1afcace2011-07-09 17:41:24 +0000280 Type *Result = 0;
281 if (ParseStructDefinition(TypeLoc, "",
282 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000283
Chris Lattner1afcace2011-07-09 17:41:24 +0000284 if (!isa<StructType>(Result)) {
285 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
286 if (Entry.first)
287 return Error(TypeLoc, "non-struct types may not be recursive");
288 Entry.first = Result;
289 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000290 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000291
Chris Lattnerdf986172009-01-02 07:01:27 +0000292 return false;
293}
294
Chris Lattner1afcace2011-07-09 17:41:24 +0000295
Chris Lattnerdf986172009-01-02 07:01:27 +0000296/// toplevelentity
297/// ::= LocalVar '=' 'type' type
298bool LLParser::ParseNamedType() {
299 std::string Name = Lex.getStrVal();
300 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000301 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000302
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000303 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000304 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000305 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000306
Chris Lattner1afcace2011-07-09 17:41:24 +0000307 Type *Result = 0;
308 if (ParseStructDefinition(NameLoc, Name,
309 NamedTypes[Name], Result)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000310
Chris Lattner1afcace2011-07-09 17:41:24 +0000311 if (!isa<StructType>(Result)) {
312 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
313 if (Entry.first)
314 return Error(NameLoc, "non-struct types may not be recursive");
315 Entry.first = Result;
316 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000317 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000318
Chris Lattner1afcace2011-07-09 17:41:24 +0000319 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000320}
321
322
323/// toplevelentity
324/// ::= 'declare' FunctionHeader
325bool LLParser::ParseDeclare() {
326 assert(Lex.getKind() == lltok::kw_declare);
327 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000328
Chris Lattnerdf986172009-01-02 07:01:27 +0000329 Function *F;
330 return ParseFunctionHeader(F, false);
331}
332
333/// toplevelentity
334/// ::= 'define' FunctionHeader '{' ...
335bool LLParser::ParseDefine() {
336 assert(Lex.getKind() == lltok::kw_define);
337 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000338
Chris Lattnerdf986172009-01-02 07:01:27 +0000339 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000340 return ParseFunctionHeader(F, true) ||
341 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000342}
343
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000344/// ParseGlobalType
345/// ::= 'constant'
346/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000347bool LLParser::ParseGlobalType(bool &IsConstant) {
348 if (Lex.getKind() == lltok::kw_constant)
349 IsConstant = true;
350 else if (Lex.getKind() == lltok::kw_global)
351 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000352 else {
353 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000354 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000355 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000356 Lex.Lex();
357 return false;
358}
359
Dan Gohman3845e502009-08-12 23:32:33 +0000360/// ParseUnnamedGlobal:
361/// OptionalVisibility ALIAS ...
362/// OptionalLinkage OptionalVisibility ... -> global variable
363/// GlobalID '=' OptionalVisibility ALIAS ...
364/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
365bool LLParser::ParseUnnamedGlobal() {
366 unsigned VarID = NumberedVals.size();
367 std::string Name;
368 LocTy NameLoc = Lex.getLoc();
369
370 // Handle the GlobalID form.
371 if (Lex.getKind() == lltok::GlobalID) {
372 if (Lex.getUIntVal() != VarID)
373 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000374 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000375 Lex.Lex(); // eat GlobalID;
376
377 if (ParseToken(lltok::equal, "expected '=' after name"))
378 return true;
379 }
380
381 bool HasLinkage;
382 unsigned Linkage, Visibility;
383 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
384 ParseOptionalVisibility(Visibility))
385 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000386
Dan Gohman3845e502009-08-12 23:32:33 +0000387 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
388 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
389 return ParseAlias(Name, NameLoc, Visibility);
390}
391
Chris Lattnerdf986172009-01-02 07:01:27 +0000392/// ParseNamedGlobal:
393/// GlobalVar '=' OptionalVisibility ALIAS ...
394/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
395bool LLParser::ParseNamedGlobal() {
396 assert(Lex.getKind() == lltok::GlobalVar);
397 LocTy NameLoc = Lex.getLoc();
398 std::string Name = Lex.getStrVal();
399 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000400
Chris Lattnerdf986172009-01-02 07:01:27 +0000401 bool HasLinkage;
402 unsigned Linkage, Visibility;
403 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
404 ParseOptionalLinkage(Linkage, HasLinkage) ||
405 ParseOptionalVisibility(Visibility))
406 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000407
Chris Lattnerdf986172009-01-02 07:01:27 +0000408 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
409 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
410 return ParseAlias(Name, NameLoc, Visibility);
411}
412
Devang Patel256be962009-07-20 19:00:08 +0000413// MDString:
414// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000415bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000416 std::string Str;
417 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000418 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000419 return false;
420}
421
422// MDNode:
423// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000424//
425/// This version of ParseMDNodeID returns the slot number and null in the case
426/// of a forward reference.
427bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
428 // !{ ..., !42, ... }
429 if (ParseUInt32(SlotNo)) return true;
430
431 // Check existing MDNode.
432 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
433 Result = NumberedMetadata[SlotNo];
434 else
435 Result = 0;
436 return false;
437}
438
Chris Lattner4a72efc2009-12-30 04:15:23 +0000439bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000440 // !{ ..., !42, ... }
441 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000442 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000443
Chris Lattner449c3102010-04-01 05:14:45 +0000444 // If not a forward reference, just return it now.
445 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000446
Chris Lattner449c3102010-04-01 05:14:45 +0000447 // Otherwise, create MDNode forward reference.
Jay Foadec9186b2011-04-21 19:59:31 +0000448 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Patel256be962009-07-20 19:00:08 +0000449 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Michael Ilseman407a6162012-11-15 22:34:00 +0000450
Chris Lattner0834e6a2009-12-30 04:51:58 +0000451 if (NumberedMetadata.size() <= MID)
452 NumberedMetadata.resize(MID+1);
453 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000454 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000455 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000456}
Devang Patel256be962009-07-20 19:00:08 +0000457
Chris Lattner84d03b12009-12-29 22:35:39 +0000458/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000459/// !foo = !{ !1, !2 }
460bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000461 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000462 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000463 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000464
Chris Lattner84d03b12009-12-29 22:35:39 +0000465 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000466 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000467 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000468 return true;
469
Dan Gohman17aa92c2010-07-21 23:38:33 +0000470 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000471 if (Lex.getKind() != lltok::rbrace)
472 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000473 if (ParseToken(lltok::exclaim, "Expected '!' here"))
474 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +0000475
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000476 MDNode *N = 0;
477 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000478 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000479 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000480
481 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
482 return true;
483
Devang Pateleff2ab62009-07-29 00:34:02 +0000484 return false;
485}
486
Devang Patel923078c2009-07-01 19:21:12 +0000487/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000488/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000489bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000490 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000491 Lex.Lex();
492 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000493
494 LocTy TyLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +0000495 Type *Ty = 0;
Devang Patel104cf9e2009-07-23 01:07:34 +0000496 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000497 if (ParseUInt32(MetadataID) ||
498 ParseToken(lltok::equal, "expected '=' here") ||
499 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000500 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000501 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000502 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000503 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000504 return true;
505
Jay Foadec9186b2011-04-21 19:59:31 +0000506 MDNode *Init = MDNode::get(Context, Elts);
Michael Ilseman407a6162012-11-15 22:34:00 +0000507
Chris Lattner0834e6a2009-12-30 04:51:58 +0000508 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000509 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000510 FI = ForwardRefMDNodes.find(MetadataID);
511 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000512 MDNode *Temp = FI->second.first;
513 Temp->replaceAllUsesWith(Init);
514 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000515 ForwardRefMDNodes.erase(FI);
Michael Ilseman407a6162012-11-15 22:34:00 +0000516
Chris Lattner0834e6a2009-12-30 04:51:58 +0000517 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
518 } else {
519 if (MetadataID >= NumberedMetadata.size())
520 NumberedMetadata.resize(MetadataID+1);
521
522 if (NumberedMetadata[MetadataID] != 0)
523 return TokError("Metadata id is already used");
524 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000525 }
526
Devang Patel923078c2009-07-01 19:21:12 +0000527 return false;
528}
529
Chris Lattnerdf986172009-01-02 07:01:27 +0000530/// ParseAlias:
531/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
532/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000533/// ::= TypeAndValue
534/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000535/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000536///
537/// Everything through visibility has already been parsed.
538///
539bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
540 unsigned Visibility) {
541 assert(Lex.getKind() == lltok::kw_alias);
542 Lex.Lex();
543 unsigned Linkage;
544 LocTy LinkageLoc = Lex.getLoc();
545 if (ParseOptionalLinkage(Linkage))
546 return true;
547
548 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000549 Linkage != GlobalValue::WeakAnyLinkage &&
550 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000551 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000552 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000553 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling32811be2012-08-17 18:33:14 +0000554 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000555 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000556
Chris Lattnerdf986172009-01-02 07:01:27 +0000557 Constant *Aliasee;
558 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000559 if (Lex.getKind() != lltok::kw_bitcast &&
560 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000561 if (ParseGlobalTypeAndValue(Aliasee)) return true;
562 } else {
563 // The bitcast dest type is not present, it is implied by the dest type.
564 ValID ID;
565 if (ParseValID(ID)) return true;
566 if (ID.Kind != ValID::t_Constant)
567 return Error(AliaseeLoc, "invalid aliasee");
568 Aliasee = ID.ConstantVal;
569 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000570
Duncan Sands1df98592010-02-16 11:11:14 +0000571 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000572 return Error(AliaseeLoc, "alias must have pointer type");
573
574 // Okay, create the alias but do not insert it into the module yet.
575 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
576 (GlobalValue::LinkageTypes)Linkage, Name,
577 Aliasee);
578 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000579
Chris Lattnerdf986172009-01-02 07:01:27 +0000580 // See if this value already exists in the symbol table. If so, it is either
581 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000582 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000583 // See if this was a redefinition. If so, there is no entry in
584 // ForwardRefVals.
585 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
586 I = ForwardRefVals.find(Name);
587 if (I == ForwardRefVals.end())
588 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
589
590 // Otherwise, this was a definition of forward ref. Verify that types
591 // agree.
592 if (Val->getType() != GA->getType())
593 return Error(NameLoc,
594 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000595
Chris Lattnerdf986172009-01-02 07:01:27 +0000596 // If they agree, just RAUW the old value with the alias and remove the
597 // forward ref info.
598 Val->replaceAllUsesWith(GA);
599 Val->eraseFromParent();
600 ForwardRefVals.erase(I);
601 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000602
Chris Lattnerdf986172009-01-02 07:01:27 +0000603 // Insert into the module, we know its name won't collide now.
604 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000605 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000606
Chris Lattnerdf986172009-01-02 07:01:27 +0000607 return false;
608}
609
610/// ParseGlobal
611/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000612/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000613/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000614/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000615///
616/// Everything through visibility has been parsed already.
617///
618bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
619 unsigned Linkage, bool HasLinkage,
620 unsigned Visibility) {
621 unsigned AddrSpace;
Hans Wennborgce718ff2012-06-23 11:37:03 +0000622 bool IsConstant, UnnamedAddr;
623 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000624 LocTy UnnamedAddrLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000625 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000626
Chris Lattner1afcace2011-07-09 17:41:24 +0000627 Type *Ty = 0;
Hans Wennborgce718ff2012-06-23 11:37:03 +0000628 if (ParseOptionalThreadLocal(TLM) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000629 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000630 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
631 &UnnamedAddrLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000632 ParseGlobalType(IsConstant) ||
633 ParseType(Ty, TyLoc))
634 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000635
Chris Lattnerdf986172009-01-02 07:01:27 +0000636 // If the linkage is specified and is external, then no initializer is
637 // present.
638 Constant *Init = 0;
639 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000640 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000641 Linkage != GlobalValue::ExternalLinkage)) {
642 if (ParseGlobalValue(Ty, Init))
643 return true;
644 }
645
Duncan Sands1df98592010-02-16 11:11:14 +0000646 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000647 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000648
Chris Lattnerdf986172009-01-02 07:01:27 +0000649 GlobalVariable *GV = 0;
650
651 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000652 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000653 if (GlobalValue *GVal = M->getNamedValue(Name)) {
654 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
655 return Error(NameLoc, "redefinition of global '@" + Name + "'");
656 GV = cast<GlobalVariable>(GVal);
657 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000658 } else {
659 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
660 I = ForwardRefValIDs.find(NumberedVals.size());
661 if (I != ForwardRefValIDs.end()) {
662 GV = cast<GlobalVariable>(I->second.first);
663 ForwardRefValIDs.erase(I);
664 }
665 }
666
667 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000668 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000669 Name, 0, GlobalVariable::NotThreadLocal,
670 AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000671 } else {
672 if (GV->getType()->getElementType() != Ty)
673 return Error(TyLoc,
674 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000675
Chris Lattnerdf986172009-01-02 07:01:27 +0000676 // Move the forward-reference to the correct spot in the module.
677 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
678 }
679
680 if (Name.empty())
681 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000682
Chris Lattnerdf986172009-01-02 07:01:27 +0000683 // Set the parsed properties on the global.
684 if (Init)
685 GV->setInitializer(Init);
686 GV->setConstant(IsConstant);
687 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
688 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Hans Wennborgce718ff2012-06-23 11:37:03 +0000689 GV->setThreadLocalMode(TLM);
Rafael Espindolabea46262011-01-08 16:42:36 +0000690 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000691
Chris Lattnerdf986172009-01-02 07:01:27 +0000692 // Parse attributes on the global.
693 while (Lex.getKind() == lltok::comma) {
694 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000695
Chris Lattnerdf986172009-01-02 07:01:27 +0000696 if (Lex.getKind() == lltok::kw_section) {
697 Lex.Lex();
698 GV->setSection(Lex.getStrVal());
699 if (ParseToken(lltok::StringConstant, "expected global section string"))
700 return true;
701 } else if (Lex.getKind() == lltok::kw_align) {
702 unsigned Alignment;
703 if (ParseOptionalAlignment(Alignment)) return true;
704 GV->setAlignment(Alignment);
705 } else {
706 TokError("unknown global variable property!");
707 }
708 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000709
Chris Lattnerdf986172009-01-02 07:01:27 +0000710 return false;
711}
712
713
714//===----------------------------------------------------------------------===//
715// GlobalValue Reference/Resolution Routines.
716//===----------------------------------------------------------------------===//
717
718/// GetGlobalVal - Get a value with the specified name or ID, creating a
719/// forward reference record if needed. This can return null if the value
720/// exists but does not have the right type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000721GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +0000722 LocTy Loc) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000723 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000724 if (PTy == 0) {
725 Error(Loc, "global variable reference must have pointer type");
726 return 0;
727 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000728
Chris Lattnerdf986172009-01-02 07:01:27 +0000729 // Look this name up in the normal function symbol table.
730 GlobalValue *Val =
731 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000732
Chris Lattnerdf986172009-01-02 07:01:27 +0000733 // If this is a forward reference for the value, see if we already created a
734 // forward ref record.
735 if (Val == 0) {
736 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
737 I = ForwardRefVals.find(Name);
738 if (I != ForwardRefVals.end())
739 Val = I->second.first;
740 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000741
Chris Lattnerdf986172009-01-02 07:01:27 +0000742 // If we have the value in the symbol table or fwd-ref table, return it.
743 if (Val) {
744 if (Val->getType() == Ty) return Val;
745 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000746 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000747 return 0;
748 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000749
Chris Lattnerdf986172009-01-02 07:01:27 +0000750 // Otherwise, create a new forward reference for this value and remember it.
751 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000752 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000753 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000754 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000755 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Justin Holewinskieaff2d52012-11-16 21:03:47 +0000756 GlobalValue::ExternalWeakLinkage, 0, Name,
757 0, GlobalVariable::NotThreadLocal,
758 PTy->getAddressSpace());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000759
Chris Lattnerdf986172009-01-02 07:01:27 +0000760 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
761 return FwdVal;
762}
763
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000764GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
765 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000766 if (PTy == 0) {
767 Error(Loc, "global variable reference must have pointer type");
768 return 0;
769 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000770
Chris Lattnerdf986172009-01-02 07:01:27 +0000771 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000772
Chris Lattnerdf986172009-01-02 07:01:27 +0000773 // If this is a forward reference for the value, see if we already created a
774 // forward ref record.
775 if (Val == 0) {
776 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
777 I = ForwardRefValIDs.find(ID);
778 if (I != ForwardRefValIDs.end())
779 Val = I->second.first;
780 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000781
Chris Lattnerdf986172009-01-02 07:01:27 +0000782 // If we have the value in the symbol table or fwd-ref table, return it.
783 if (Val) {
784 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000785 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000786 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000787 return 0;
788 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000789
Chris Lattnerdf986172009-01-02 07:01:27 +0000790 // Otherwise, create a new forward reference for this value and remember it.
791 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000792 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000793 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000794 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000795 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
796 GlobalValue::ExternalWeakLinkage, 0, "");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000797
Chris Lattnerdf986172009-01-02 07:01:27 +0000798 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
799 return FwdVal;
800}
801
802
803//===----------------------------------------------------------------------===//
804// Helper Routines.
805//===----------------------------------------------------------------------===//
806
807/// ParseToken - If the current token has the specified kind, eat it and return
808/// success. Otherwise, emit the specified error and return failure.
809bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
810 if (Lex.getKind() != T)
811 return TokError(ErrMsg);
812 Lex.Lex();
813 return false;
814}
815
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000816/// ParseStringConstant
817/// ::= StringConstant
818bool LLParser::ParseStringConstant(std::string &Result) {
819 if (Lex.getKind() != lltok::StringConstant)
820 return TokError("expected string constant");
821 Result = Lex.getStrVal();
822 Lex.Lex();
823 return false;
824}
825
826/// ParseUInt32
827/// ::= uint32
828bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000829 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
830 return TokError("expected integer");
831 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
832 if (Val64 != unsigned(Val64))
833 return TokError("expected 32-bit integer (too large)");
834 Val = Val64;
835 Lex.Lex();
836 return false;
837}
838
Hans Wennborgce718ff2012-06-23 11:37:03 +0000839/// ParseTLSModel
840/// := 'localdynamic'
841/// := 'initialexec'
842/// := 'localexec'
843bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
844 switch (Lex.getKind()) {
845 default:
846 return TokError("expected localdynamic, initialexec or localexec");
847 case lltok::kw_localdynamic:
848 TLM = GlobalVariable::LocalDynamicTLSModel;
849 break;
850 case lltok::kw_initialexec:
851 TLM = GlobalVariable::InitialExecTLSModel;
852 break;
853 case lltok::kw_localexec:
854 TLM = GlobalVariable::LocalExecTLSModel;
855 break;
856 }
857
858 Lex.Lex();
859 return false;
860}
861
862/// ParseOptionalThreadLocal
863/// := /*empty*/
864/// := 'thread_local'
865/// := 'thread_local' '(' tlsmodel ')'
866bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
867 TLM = GlobalVariable::NotThreadLocal;
868 if (!EatIfPresent(lltok::kw_thread_local))
869 return false;
870
871 TLM = GlobalVariable::GeneralDynamicTLSModel;
872 if (Lex.getKind() == lltok::lparen) {
873 Lex.Lex();
874 return ParseTLSModel(TLM) ||
875 ParseToken(lltok::rparen, "expected ')' after thread local model");
876 }
877 return false;
878}
Chris Lattnerdf986172009-01-02 07:01:27 +0000879
880/// ParseOptionalAddrSpace
881/// := /*empty*/
882/// := 'addrspace' '(' uint32 ')'
883bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
884 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000885 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000886 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000887 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000888 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000889 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000890}
Chris Lattnerdf986172009-01-02 07:01:27 +0000891
892/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
893/// indicates what kind of attribute list this is: 0: function arg, 1: result,
894/// 2: function attr.
Bill Wendling702cc912012-10-15 20:35:56 +0000895bool LLParser::ParseOptionalAttrs(AttrBuilder &B, unsigned AttrKind) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000896 LocTy AttrLoc = Lex.getLoc();
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000897 bool HaveError = false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000898
Bill Wendlingf385f4c2012-10-08 23:27:46 +0000899 B.clear();
900
Chris Lattnerdf986172009-01-02 07:01:27 +0000901 while (1) {
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000902 lltok::Kind Token = Lex.getKind();
903 switch (Token) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000904 default: // End of attributes.
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000905 return HaveError;
Bill Wendling2e879bc2012-10-09 09:11:20 +0000906 case lltok::kw_zeroext: B.addAttribute(Attributes::ZExt); break;
907 case lltok::kw_signext: B.addAttribute(Attributes::SExt); break;
908 case lltok::kw_inreg: B.addAttribute(Attributes::InReg); break;
909 case lltok::kw_sret: B.addAttribute(Attributes::StructRet); break;
910 case lltok::kw_noalias: B.addAttribute(Attributes::NoAlias); break;
911 case lltok::kw_nocapture: B.addAttribute(Attributes::NoCapture); break;
912 case lltok::kw_byval: B.addAttribute(Attributes::ByVal); break;
913 case lltok::kw_nest: B.addAttribute(Attributes::Nest); break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000914
Bill Wendling2e879bc2012-10-09 09:11:20 +0000915 case lltok::kw_noreturn: B.addAttribute(Attributes::NoReturn); break;
916 case lltok::kw_nounwind: B.addAttribute(Attributes::NoUnwind); break;
917 case lltok::kw_uwtable: B.addAttribute(Attributes::UWTable); break;
918 case lltok::kw_returns_twice: B.addAttribute(Attributes::ReturnsTwice); break;
919 case lltok::kw_noinline: B.addAttribute(Attributes::NoInline); break;
920 case lltok::kw_readnone: B.addAttribute(Attributes::ReadNone); break;
921 case lltok::kw_readonly: B.addAttribute(Attributes::ReadOnly); break;
922 case lltok::kw_inlinehint: B.addAttribute(Attributes::InlineHint); break;
923 case lltok::kw_alwaysinline: B.addAttribute(Attributes::AlwaysInline); break;
924 case lltok::kw_optsize: B.addAttribute(Attributes::OptimizeForSize); break;
925 case lltok::kw_ssp: B.addAttribute(Attributes::StackProtect); break;
926 case lltok::kw_sspreq: B.addAttribute(Attributes::StackProtectReq); break;
927 case lltok::kw_noredzone: B.addAttribute(Attributes::NoRedZone); break;
928 case lltok::kw_noimplicitfloat: B.addAttribute(Attributes::NoImplicitFloat); break;
929 case lltok::kw_naked: B.addAttribute(Attributes::Naked); break;
930 case lltok::kw_nonlazybind: B.addAttribute(Attributes::NonLazyBind); break;
931 case lltok::kw_address_safety: B.addAttribute(Attributes::AddressSafety); break;
Quentin Colombet9a419f62012-10-30 16:32:52 +0000932 case lltok::kw_minsize: B.addAttribute(Attributes::MinSize); break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000933
Charles Davis1e063d12010-02-12 00:31:15 +0000934 case lltok::kw_alignstack: {
935 unsigned Alignment;
936 if (ParseOptionalStackAlignment(Alignment))
937 return true;
Bill Wendling03272442012-10-08 22:20:14 +0000938 B.addStackAlignmentAttr(Alignment);
Charles Davis1e063d12010-02-12 00:31:15 +0000939 continue;
940 }
941
Chris Lattnerdf986172009-01-02 07:01:27 +0000942 case lltok::kw_align: {
943 unsigned Alignment;
944 if (ParseOptionalAlignment(Alignment))
945 return true;
Bill Wendling03272442012-10-08 22:20:14 +0000946 B.addAlignmentAttr(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000947 continue;
948 }
Charles Davis1e063d12010-02-12 00:31:15 +0000949
Chris Lattnerdf986172009-01-02 07:01:27 +0000950 }
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000951
952 // Perform some error checking.
953 switch (Token) {
954 default:
955 if (AttrKind == 2)
956 HaveError |= Error(AttrLoc, "invalid use of attribute on a function");
957 break;
958 case lltok::kw_align:
959 // As a hack, we allow "align 2" on functions as a synonym for
960 // "alignstack 2".
961 break;
962
963 // Parameter Only:
964 case lltok::kw_sret:
965 case lltok::kw_nocapture:
966 case lltok::kw_byval:
967 case lltok::kw_nest:
968 if (AttrKind != 0)
969 HaveError |= Error(AttrLoc, "invalid use of parameter-only attribute");
970 break;
971
972 // Function Only:
973 case lltok::kw_noreturn:
974 case lltok::kw_nounwind:
975 case lltok::kw_readnone:
976 case lltok::kw_readonly:
977 case lltok::kw_noinline:
978 case lltok::kw_alwaysinline:
979 case lltok::kw_optsize:
980 case lltok::kw_ssp:
981 case lltok::kw_sspreq:
982 case lltok::kw_noredzone:
983 case lltok::kw_noimplicitfloat:
984 case lltok::kw_naked:
985 case lltok::kw_inlinehint:
986 case lltok::kw_alignstack:
987 case lltok::kw_uwtable:
988 case lltok::kw_nonlazybind:
989 case lltok::kw_returns_twice:
990 case lltok::kw_address_safety:
Quentin Colombet9a419f62012-10-30 16:32:52 +0000991 case lltok::kw_minsize:
Bill Wendlingdc998cc2012-09-28 22:30:18 +0000992 if (AttrKind != 2)
993 HaveError |= Error(AttrLoc, "invalid use of function-only attribute");
994 break;
995 }
996
Chris Lattnerdf986172009-01-02 07:01:27 +0000997 Lex.Lex();
998 }
999}
1000
1001/// ParseOptionalLinkage
1002/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001003/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001004/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001005/// ::= 'linker_private_weak'
Chris Lattnerdf986172009-01-02 07:01:27 +00001006/// ::= 'internal'
1007/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001008/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001009/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001010/// ::= 'linkonce_odr'
Bill Wendling32811be2012-08-17 18:33:14 +00001011/// ::= 'linkonce_odr_auto_hide'
Bill Wendling5e721d72010-07-01 21:55:59 +00001012/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001013/// ::= 'appending'
1014/// ::= 'dllexport'
1015/// ::= 'common'
1016/// ::= 'dllimport'
1017/// ::= 'extern_weak'
1018/// ::= 'external'
1019bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1020 HasLinkage = false;
1021 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001022 default: Res=GlobalValue::ExternalLinkage; return false;
1023 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1024 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001025 case lltok::kw_linker_private_weak:
1026 Res = GlobalValue::LinkerPrivateWeakLinkage;
1027 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001028 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1029 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1030 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1031 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1032 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Bill Wendling32811be2012-08-17 18:33:14 +00001033 case lltok::kw_linkonce_odr_auto_hide:
1034 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1035 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1036 break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001037 case lltok::kw_available_externally:
1038 Res = GlobalValue::AvailableExternallyLinkage;
1039 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001040 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1041 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1042 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1043 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1044 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1045 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001046 }
1047 Lex.Lex();
1048 HasLinkage = true;
1049 return false;
1050}
1051
1052/// ParseOptionalVisibility
1053/// ::= /*empty*/
1054/// ::= 'default'
1055/// ::= 'hidden'
1056/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001057///
Chris Lattnerdf986172009-01-02 07:01:27 +00001058bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1059 switch (Lex.getKind()) {
1060 default: Res = GlobalValue::DefaultVisibility; return false;
1061 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1062 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1063 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1064 }
1065 Lex.Lex();
1066 return false;
1067}
1068
1069/// ParseOptionalCallingConv
1070/// ::= /*empty*/
1071/// ::= 'ccc'
1072/// ::= 'fastcc'
Elena Demikhovsky35752222012-10-24 14:46:16 +00001073/// ::= 'kw_intel_ocl_bicc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001074/// ::= 'coldcc'
1075/// ::= 'x86_stdcallcc'
1076/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001077/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001078/// ::= 'arm_apcscc'
1079/// ::= 'arm_aapcscc'
1080/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001081/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001082/// ::= 'ptx_kernel'
1083/// ::= 'ptx_device'
Micah Villmowe53d6052012-10-01 17:01:31 +00001084/// ::= 'spir_func'
1085/// ::= 'spir_kernel'
Chris Lattnerdf986172009-01-02 07:01:27 +00001086/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001087///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001088bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001089 switch (Lex.getKind()) {
1090 default: CC = CallingConv::C; return false;
1091 case lltok::kw_ccc: CC = CallingConv::C; break;
1092 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1093 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1094 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1095 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001096 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001097 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1098 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1099 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001100 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001101 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1102 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmowe53d6052012-10-01 17:01:31 +00001103 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1104 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovsky35752222012-10-24 14:46:16 +00001105 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001106 case lltok::kw_cc: {
1107 unsigned ArbitraryCC;
1108 Lex.Lex();
David Blaikie4d6ccb52012-01-20 21:51:11 +00001109 if (ParseUInt32(ArbitraryCC))
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001110 return true;
David Blaikie4d6ccb52012-01-20 21:51:11 +00001111 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1112 return false;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001113 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001114 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001115
Chris Lattnerdf986172009-01-02 07:01:27 +00001116 Lex.Lex();
1117 return false;
1118}
1119
Chris Lattnerb8c46862009-12-30 05:31:19 +00001120/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001121/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001122bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1123 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001124 do {
1125 if (Lex.getKind() != lltok::MetadataVar)
1126 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001127
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001128 std::string Name = Lex.getStrVal();
Benjamin Kramer85dadec2011-12-06 11:50:26 +00001129 unsigned MDK = M->getMDKindID(Name);
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001130 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001131
Chris Lattner442ffa12009-12-29 21:53:55 +00001132 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001133 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001134
1135 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001136 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001137
Dan Gohman68261142010-08-24 14:35:45 +00001138 // This code is similar to that of ParseMetadataValue, however it needs to
1139 // have special-case code for a forward reference; see the comments on
1140 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1141 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001142 if (Lex.getKind() == lltok::lbrace) {
1143 ValID ID;
1144 if (ParseMetadataListValue(ID, PFS))
1145 return true;
1146 assert(ID.Kind == ValID::t_MDNode);
1147 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001148 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001149 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001150 if (ParseMDNodeID(Node, NodeID))
1151 return true;
1152 if (Node) {
1153 // If we got the node, add it to the instruction.
1154 Inst->setMetadata(MDK, Node);
1155 } else {
1156 MDRef R = { Loc, MDK, NodeID };
1157 // Otherwise, remember that this should be resolved later.
1158 ForwardRefInstMetadata[Inst].push_back(R);
1159 }
Chris Lattner449c3102010-04-01 05:14:45 +00001160 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001161
1162 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001163 } while (EatIfPresent(lltok::comma));
1164 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001165}
1166
Chris Lattnerdf986172009-01-02 07:01:27 +00001167/// ParseOptionalAlignment
1168/// ::= /* empty */
1169/// ::= 'align' 4
1170bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1171 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001172 if (!EatIfPresent(lltok::kw_align))
1173 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001174 LocTy AlignLoc = Lex.getLoc();
1175 if (ParseUInt32(Alignment)) return true;
1176 if (!isPowerOf2_32(Alignment))
1177 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001178 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001179 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001180 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001181}
1182
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001183/// ParseOptionalCommaAlign
Michael Ilseman407a6162012-11-15 22:34:00 +00001184/// ::=
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001185/// ::= ',' align 4
1186///
1187/// This returns with AteExtraComma set to true if it ate an excess comma at the
1188/// end.
1189bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1190 bool &AteExtraComma) {
1191 AteExtraComma = false;
1192 while (EatIfPresent(lltok::comma)) {
1193 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001194 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001195 AteExtraComma = true;
1196 return false;
1197 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001198
Chris Lattner093eed12010-04-23 00:50:50 +00001199 if (Lex.getKind() != lltok::kw_align)
1200 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001201
Chris Lattner093eed12010-04-23 00:50:50 +00001202 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001203 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001204
Devang Patelf633a062009-09-17 23:04:48 +00001205 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001206}
1207
Eli Friedman47f35132011-07-25 23:16:38 +00001208/// ParseScopeAndOrdering
1209/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1210/// else: ::=
1211///
1212/// This sets Scope and Ordering to the parsed values.
1213bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1214 AtomicOrdering &Ordering) {
1215 if (!isAtomic)
1216 return false;
1217
1218 Scope = CrossThread;
1219 if (EatIfPresent(lltok::kw_singlethread))
1220 Scope = SingleThread;
1221 switch (Lex.getKind()) {
1222 default: return TokError("Expected ordering on atomic instruction");
1223 case lltok::kw_unordered: Ordering = Unordered; break;
1224 case lltok::kw_monotonic: Ordering = Monotonic; break;
1225 case lltok::kw_acquire: Ordering = Acquire; break;
1226 case lltok::kw_release: Ordering = Release; break;
1227 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1228 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1229 }
1230 Lex.Lex();
1231 return false;
1232}
1233
Charles Davis1e063d12010-02-12 00:31:15 +00001234/// ParseOptionalStackAlignment
1235/// ::= /* empty */
1236/// ::= 'alignstack' '(' 4 ')'
1237bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1238 Alignment = 0;
1239 if (!EatIfPresent(lltok::kw_alignstack))
1240 return false;
1241 LocTy ParenLoc = Lex.getLoc();
1242 if (!EatIfPresent(lltok::lparen))
1243 return Error(ParenLoc, "expected '('");
1244 LocTy AlignLoc = Lex.getLoc();
1245 if (ParseUInt32(Alignment)) return true;
1246 ParenLoc = Lex.getLoc();
1247 if (!EatIfPresent(lltok::rparen))
1248 return Error(ParenLoc, "expected ')'");
1249 if (!isPowerOf2_32(Alignment))
1250 return Error(AlignLoc, "stack alignment is not a power of two");
1251 return false;
1252}
Devang Patelf633a062009-09-17 23:04:48 +00001253
Chris Lattner628c13a2009-12-30 05:14:00 +00001254/// ParseIndexList - This parses the index list for an insert/extractvalue
1255/// instruction. This sets AteExtraComma in the case where we eat an extra
1256/// comma at the end of the line and find that it is followed by metadata.
1257/// Clients that don't allow metadata can call the version of this function that
1258/// only takes one argument.
1259///
Chris Lattnerdf986172009-01-02 07:01:27 +00001260/// ParseIndexList
1261/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001262///
1263bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1264 bool &AteExtraComma) {
1265 AteExtraComma = false;
Michael Ilseman407a6162012-11-15 22:34:00 +00001266
Chris Lattnerdf986172009-01-02 07:01:27 +00001267 if (Lex.getKind() != lltok::comma)
1268 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001269
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001270 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001271 if (Lex.getKind() == lltok::MetadataVar) {
1272 AteExtraComma = true;
1273 return false;
1274 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001275 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001276 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001277 Indices.push_back(Idx);
1278 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001279
Chris Lattnerdf986172009-01-02 07:01:27 +00001280 return false;
1281}
1282
1283//===----------------------------------------------------------------------===//
1284// Type Parsing.
1285//===----------------------------------------------------------------------===//
1286
Chris Lattner1afcace2011-07-09 17:41:24 +00001287/// ParseType - Parse a type.
1288bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1289 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001290 switch (Lex.getKind()) {
1291 default:
1292 return TokError("expected type");
1293 case lltok::Type:
Chris Lattner1afcace2011-07-09 17:41:24 +00001294 // Type ::= 'float' | 'void' (etc)
Chris Lattnerdf986172009-01-02 07:01:27 +00001295 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001296 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001297 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001298 case lltok::lbrace:
Chris Lattner1afcace2011-07-09 17:41:24 +00001299 // Type ::= StructType
1300 if (ParseAnonStructType(Result, false))
Chris Lattnerdf986172009-01-02 07:01:27 +00001301 return true;
1302 break;
1303 case lltok::lsquare:
Chris Lattner1afcace2011-07-09 17:41:24 +00001304 // Type ::= '[' ... ']'
Chris Lattnerdf986172009-01-02 07:01:27 +00001305 Lex.Lex(); // eat the lsquare.
1306 if (ParseArrayVectorType(Result, false))
1307 return true;
1308 break;
1309 case lltok::less: // Either vector or packed struct.
Chris Lattner1afcace2011-07-09 17:41:24 +00001310 // Type ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001311 Lex.Lex();
1312 if (Lex.getKind() == lltok::lbrace) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001313 if (ParseAnonStructType(Result, true) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001314 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001315 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001316 } else if (ParseArrayVectorType(Result, true))
1317 return true;
1318 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001319 case lltok::LocalVar: {
1320 // Type ::= %foo
1321 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman407a6162012-11-15 22:34:00 +00001322
Chris Lattner1afcace2011-07-09 17:41:24 +00001323 // If the type hasn't been defined yet, create a forward definition and
1324 // remember where that forward def'n was seen (in case it never is defined).
1325 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001326 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattner1afcace2011-07-09 17:41:24 +00001327 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001328 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001329 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001330 Lex.Lex();
1331 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001332 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001333
Chris Lattner1afcace2011-07-09 17:41:24 +00001334 case lltok::LocalVarID: {
1335 // Type ::= %4
1336 if (Lex.getUIntVal() >= NumberedTypes.size())
1337 NumberedTypes.resize(Lex.getUIntVal()+1);
1338 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman407a6162012-11-15 22:34:00 +00001339
Chris Lattner1afcace2011-07-09 17:41:24 +00001340 // If the type hasn't been defined yet, create a forward definition and
1341 // remember where that forward def'n was seen (in case it never is defined).
1342 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001343 Entry.first = StructType::create(Context);
Chris Lattner1afcace2011-07-09 17:41:24 +00001344 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001345 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001346 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001347 Lex.Lex();
1348 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001349 }
1350 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001351
1352 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001353 while (1) {
1354 switch (Lex.getKind()) {
1355 // End of type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001356 default:
1357 if (!AllowVoid && Result->isVoidTy())
1358 return Error(TypeLoc, "void type only allowed for function results");
1359 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001360
Chris Lattner1afcace2011-07-09 17:41:24 +00001361 // Type ::= Type '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001362 case lltok::star:
Chris Lattner1afcace2011-07-09 17:41:24 +00001363 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001364 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001365 if (Result->isVoidTy())
1366 return TokError("pointers to void are invalid - use i8* instead");
1367 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001368 return TokError("pointer to this type is invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001369 Result = PointerType::getUnqual(Result);
Chris Lattnerdf986172009-01-02 07:01:27 +00001370 Lex.Lex();
1371 break;
1372
Chris Lattner1afcace2011-07-09 17:41:24 +00001373 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001374 case lltok::kw_addrspace: {
Chris Lattner1afcace2011-07-09 17:41:24 +00001375 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001376 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001377 if (Result->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001378 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattner1afcace2011-07-09 17:41:24 +00001379 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001380 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001381 unsigned AddrSpace;
1382 if (ParseOptionalAddrSpace(AddrSpace) ||
1383 ParseToken(lltok::star, "expected '*' in address space"))
1384 return true;
1385
Chris Lattner1afcace2011-07-09 17:41:24 +00001386 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001387 break;
1388 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001389
Chris Lattnerdf986172009-01-02 07:01:27 +00001390 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1391 case lltok::lparen:
1392 if (ParseFunctionType(Result))
1393 return true;
1394 break;
1395 }
1396 }
1397}
1398
1399/// ParseParameterList
1400/// ::= '(' ')'
1401/// ::= '(' Arg (',' Arg)* ')'
1402/// Arg
1403/// ::= Type OptionalAttributes Value OptionalAttributes
1404bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1405 PerFunctionState &PFS) {
1406 if (ParseToken(lltok::lparen, "expected '(' in call"))
1407 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001408
Chris Lattnerdf986172009-01-02 07:01:27 +00001409 while (Lex.getKind() != lltok::rparen) {
1410 // If this isn't the first argument, we need a comma.
1411 if (!ArgList.empty() &&
1412 ParseToken(lltok::comma, "expected ',' in argument list"))
1413 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001414
Chris Lattnerdf986172009-01-02 07:01:27 +00001415 // Parse the argument.
1416 LocTy ArgLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +00001417 Type *ArgTy = 0;
Bill Wendling702cc912012-10-15 20:35:56 +00001418 AttrBuilder ArgAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001419 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001420 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001421 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001422
Chris Lattner287881d2009-12-30 02:11:14 +00001423 // Otherwise, handle normal operands.
Bill Wendling03272442012-10-08 22:20:14 +00001424 if (ParseOptionalAttrs(ArgAttrs, 0) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001425 return true;
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001426 ArgList.push_back(ParamInfo(ArgLoc, V, Attributes::get(V->getContext(),
1427 ArgAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00001428 }
1429
1430 Lex.Lex(); // Lex the ')'.
1431 return false;
1432}
1433
1434
1435
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001436/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattner1afcace2011-07-09 17:41:24 +00001437/// prototype.
Chris Lattnerdf986172009-01-02 07:01:27 +00001438/// ::= '(' ArgTypeListI ')'
1439/// ArgTypeListI
1440/// ::= /*empty*/
1441/// ::= '...'
1442/// ::= ArgTypeList ',' '...'
1443/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001444///
Chris Lattner1afcace2011-07-09 17:41:24 +00001445bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1446 bool &isVarArg){
Chris Lattnerdf986172009-01-02 07:01:27 +00001447 isVarArg = false;
1448 assert(Lex.getKind() == lltok::lparen);
1449 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001450
Chris Lattnerdf986172009-01-02 07:01:27 +00001451 if (Lex.getKind() == lltok::rparen) {
1452 // empty
1453 } else if (Lex.getKind() == lltok::dotdotdot) {
1454 isVarArg = true;
1455 Lex.Lex();
1456 } else {
1457 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001458 Type *ArgTy = 0;
Bill Wendling702cc912012-10-15 20:35:56 +00001459 AttrBuilder Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001460 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001461
Chris Lattner1afcace2011-07-09 17:41:24 +00001462 if (ParseType(ArgTy) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001463 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001464
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001465 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001466 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001467
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001468 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001469 Name = Lex.getStrVal();
1470 Lex.Lex();
1471 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001472
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001473 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001474 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001475
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001476 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1477 Attributes::get(ArgTy->getContext(),
1478 Attrs), Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001479
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001480 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001481 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001482 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001483 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001484 break;
1485 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001486
Chris Lattnerdf986172009-01-02 07:01:27 +00001487 // Otherwise must be an argument type.
1488 TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001489 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +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");
1493
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 } else {
1498 Name = "";
1499 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001500
Chris Lattner1afcace2011-07-09 17:41:24 +00001501 if (!ArgTy->isFirstClassType())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001502 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001503
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001504 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1505 Attributes::get(ArgTy->getContext(), Attrs),
1506 Name));
Chris Lattnerdf986172009-01-02 07:01:27 +00001507 }
1508 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001509
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001510 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001511}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001512
Chris Lattnerdf986172009-01-02 07:01:27 +00001513/// ParseFunctionType
1514/// ::= Type ArgumentList OptionalAttrs
Chris Lattner1afcace2011-07-09 17:41:24 +00001515bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001516 assert(Lex.getKind() == lltok::lparen);
1517
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001518 if (!FunctionType::isValidReturnType(Result))
1519 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001520
Chris Lattner1afcace2011-07-09 17:41:24 +00001521 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00001522 bool isVarArg;
Chris Lattner1afcace2011-07-09 17:41:24 +00001523 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerdf986172009-01-02 07:01:27 +00001524 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001525
Chris Lattnerdf986172009-01-02 07:01:27 +00001526 // Reject names on the arguments lists.
1527 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1528 if (!ArgList[i].Name.empty())
1529 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendling7be78482012-10-14 08:54:26 +00001530 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnera16546a2011-06-17 17:37:13 +00001531 return Error(ArgList[i].Loc,
1532 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001533 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001534
Jay Foad5fdd6c82011-07-12 14:06:48 +00001535 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerdf986172009-01-02 07:01:27 +00001536 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattner1afcace2011-07-09 17:41:24 +00001537 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001538
Chris Lattner1afcace2011-07-09 17:41:24 +00001539 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerdf986172009-01-02 07:01:27 +00001540 return false;
1541}
1542
Chris Lattner1afcace2011-07-09 17:41:24 +00001543/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1544/// other structs.
1545bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1546 SmallVector<Type*, 8> Elts;
1547 if (ParseStructBody(Elts)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001548
Chris Lattner1afcace2011-07-09 17:41:24 +00001549 Result = StructType::get(Context, Elts, Packed);
1550 return false;
1551}
1552
1553/// ParseStructDefinition - Parse a struct in a 'type' definition.
1554bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1555 std::pair<Type*, LocTy> &Entry,
1556 Type *&ResultTy) {
1557 // If the type was already defined, diagnose the redefinition.
1558 if (Entry.first && !Entry.second.isValid())
1559 return Error(TypeLoc, "redefinition of type");
Michael Ilseman407a6162012-11-15 22:34:00 +00001560
Chris Lattner1afcace2011-07-09 17:41:24 +00001561 // If we have opaque, just return without filling in the definition for the
1562 // struct. This counts as a definition as far as the .ll file goes.
1563 if (EatIfPresent(lltok::kw_opaque)) {
1564 // This type is being defined, so clear the location to indicate this.
1565 Entry.second = SMLoc();
Michael Ilseman407a6162012-11-15 22:34:00 +00001566
Chris Lattner1afcace2011-07-09 17:41:24 +00001567 // If this type number has never been uttered, create it.
1568 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001569 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001570 ResultTy = Entry.first;
1571 return false;
1572 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001573
Chris Lattner1afcace2011-07-09 17:41:24 +00001574 // If the type starts with '<', then it is either a packed struct or a vector.
1575 bool isPacked = EatIfPresent(lltok::less);
1576
1577 // If we don't have a struct, then we have a random type alias, which we
1578 // accept for compatibility with old files. These types are not allowed to be
1579 // forward referenced and not allowed to be recursive.
1580 if (Lex.getKind() != lltok::lbrace) {
1581 if (Entry.first)
1582 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman407a6162012-11-15 22:34:00 +00001583
Chris Lattner1afcace2011-07-09 17:41:24 +00001584 ResultTy = 0;
1585 if (isPacked)
1586 return ParseArrayVectorType(ResultTy, true);
1587 return ParseType(ResultTy);
1588 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001589
Chris Lattner1afcace2011-07-09 17:41:24 +00001590 // 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);
Michael Ilseman407a6162012-11-15 22:34:00 +00001596
Chris Lattner1afcace2011-07-09 17:41:24 +00001597 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman407a6162012-11-15 22:34:00 +00001598
Chris Lattner1afcace2011-07-09 17:41:24 +00001599 SmallVector<Type*, 8> Body;
1600 if (ParseStructBody(Body) ||
1601 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1602 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001603
Chris Lattner1afcace2011-07-09 17:41:24 +00001604 STy->setBody(Body, isPacked);
1605 ResultTy = STy;
1606 return false;
1607}
1608
1609
Chris Lattnerdf986172009-01-02 07:01:27 +00001610/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattner1afcace2011-07-09 17:41:24 +00001611/// StructType
Chris Lattnerdf986172009-01-02 07:01:27 +00001612/// ::= '{' '}'
Chris Lattner1afcace2011-07-09 17:41:24 +00001613/// ::= '{' Type (',' Type)* '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00001614/// ::= '<' '{' '}' '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001615/// ::= '<' '{' Type (',' Type)* '}' '>'
1616bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001617 assert(Lex.getKind() == lltok::lbrace);
1618 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001619
Chris Lattner1afcace2011-07-09 17:41:24 +00001620 // Handle the empty struct.
1621 if (EatIfPresent(lltok::rbrace))
Chris Lattnerdf986172009-01-02 07:01:27 +00001622 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001623
Chris Lattnera9a9e072009-03-09 04:49:14 +00001624 LocTy EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001625 Type *Ty = 0;
1626 if (ParseType(Ty)) return true;
1627 Body.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001628
Chris Lattner1afcace2011-07-09 17:41:24 +00001629 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001630 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001631
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001632 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001633 EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001634 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001635
Chris Lattner1afcace2011-07-09 17:41:24 +00001636 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001637 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001638
Chris Lattner1afcace2011-07-09 17:41:24 +00001639 Body.push_back(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00001640 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001641
Chris Lattner1afcace2011-07-09 17:41:24 +00001642 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerdf986172009-01-02 07:01:27 +00001643}
1644
1645/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1646/// token has already been consumed.
Chris Lattner1afcace2011-07-09 17:41:24 +00001647/// Type
Chris Lattnerdf986172009-01-02 07:01:27 +00001648/// ::= '[' APSINTVAL 'x' Types ']'
1649/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001650bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001651 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1652 Lex.getAPSIntVal().getBitWidth() > 64)
1653 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001654
Chris Lattnerdf986172009-01-02 07:01:27 +00001655 LocTy SizeLoc = Lex.getLoc();
1656 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001657 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001658
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001659 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1660 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001661
1662 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001663 Type *EltTy = 0;
1664 if (ParseType(EltTy)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001665
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001666 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1667 "expected end of sequential type"))
1668 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001669
Chris Lattnerdf986172009-01-02 07:01:27 +00001670 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001671 if (Size == 0)
1672 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001673 if ((unsigned)Size != Size)
1674 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001675 if (!VectorType::isValidElementType(EltTy))
Duncan Sands2333e292012-11-13 12:59:33 +00001676 return Error(TypeLoc, "invalid vector element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001677 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001678 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001679 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001680 return Error(TypeLoc, "invalid array element type");
Chris Lattner1afcace2011-07-09 17:41:24 +00001681 Result = ArrayType::get(EltTy, Size);
Chris Lattnerdf986172009-01-02 07:01:27 +00001682 }
1683 return false;
1684}
1685
1686//===----------------------------------------------------------------------===//
1687// Function Semantic Analysis.
1688//===----------------------------------------------------------------------===//
1689
Chris Lattner09d9ef42009-10-28 03:39:23 +00001690LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1691 int functionNumber)
1692 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001693
1694 // Insert unnamed arguments into the NumberedVals list.
1695 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1696 AI != E; ++AI)
1697 if (!AI->hasName())
1698 NumberedVals.push_back(AI);
1699}
1700
1701LLParser::PerFunctionState::~PerFunctionState() {
1702 // If there were any forward referenced non-basicblock values, delete them.
1703 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1704 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1705 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001706 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001707 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001708 delete I->second.first;
1709 I->second.first = 0;
1710 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001711
Chris Lattnerdf986172009-01-02 07:01:27 +00001712 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1713 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1714 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001715 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001716 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001717 delete I->second.first;
1718 I->second.first = 0;
1719 }
1720}
1721
Chris Lattner09d9ef42009-10-28 03:39:23 +00001722bool LLParser::PerFunctionState::FinishFunction() {
1723 // Check to see if someone took the address of labels in this block.
1724 if (!P.ForwardRefBlockAddresses.empty()) {
1725 ValID FunctionID;
1726 if (!F.getName().empty()) {
1727 FunctionID.Kind = ValID::t_GlobalName;
1728 FunctionID.StrVal = F.getName();
1729 } else {
1730 FunctionID.Kind = ValID::t_GlobalID;
1731 FunctionID.UIntVal = FunctionNumber;
1732 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001733
Chris Lattner09d9ef42009-10-28 03:39:23 +00001734 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1735 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1736 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1737 // Resolve all these references.
1738 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1739 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00001740
Chris Lattner09d9ef42009-10-28 03:39:23 +00001741 P.ForwardRefBlockAddresses.erase(FRBAI);
1742 }
1743 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001744
Chris Lattnerdf986172009-01-02 07:01:27 +00001745 if (!ForwardRefVals.empty())
1746 return P.Error(ForwardRefVals.begin()->second.second,
1747 "use of undefined value '%" + ForwardRefVals.begin()->first +
1748 "'");
1749 if (!ForwardRefValIDs.empty())
1750 return P.Error(ForwardRefValIDs.begin()->second.second,
1751 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001752 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001753 return false;
1754}
1755
1756
1757/// GetVal - Get a value with the specified name or ID, creating a
1758/// forward reference record if needed. This can return null if the value
1759/// exists but does not have the right type.
1760Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001761 Type *Ty, LocTy Loc) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001762 // Look this name up in the normal function symbol table.
1763 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001764
Chris Lattnerdf986172009-01-02 07:01:27 +00001765 // If this is a forward reference for the value, see if we already created a
1766 // forward ref record.
1767 if (Val == 0) {
1768 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1769 I = ForwardRefVals.find(Name);
1770 if (I != ForwardRefVals.end())
1771 Val = I->second.first;
1772 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001773
Chris Lattnerdf986172009-01-02 07:01:27 +00001774 // If we have the value in the symbol table or fwd-ref table, return it.
1775 if (Val) {
1776 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001777 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001778 P.Error(Loc, "'%" + Name + "' is not a basic block");
1779 else
1780 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001781 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001782 return 0;
1783 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001784
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 // Don't make placeholders with invalid type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001786 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001787 P.Error(Loc, "invalid use of a non-first-class type");
1788 return 0;
1789 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001790
Chris Lattnerdf986172009-01-02 07:01:27 +00001791 // Otherwise, create a new forward reference for this value and remember it.
1792 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001793 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001794 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001795 else
1796 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001797
Chris Lattnerdf986172009-01-02 07:01:27 +00001798 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1799 return FwdVal;
1800}
1801
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001802Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +00001803 LocTy Loc) {
1804 // Look this name up in the normal function symbol table.
1805 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001806
Chris Lattnerdf986172009-01-02 07:01:27 +00001807 // If this is a forward reference for the value, see if we already created a
1808 // forward ref record.
1809 if (Val == 0) {
1810 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1811 I = ForwardRefValIDs.find(ID);
1812 if (I != ForwardRefValIDs.end())
1813 Val = I->second.first;
1814 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001815
Chris Lattnerdf986172009-01-02 07:01:27 +00001816 // If we have the value in the symbol table or fwd-ref table, return it.
1817 if (Val) {
1818 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001819 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001820 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001821 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001822 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001823 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001824 return 0;
1825 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001826
Chris Lattner1afcace2011-07-09 17:41:24 +00001827 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001828 P.Error(Loc, "invalid use of a non-first-class type");
1829 return 0;
1830 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001831
Chris Lattnerdf986172009-01-02 07:01:27 +00001832 // Otherwise, create a new forward reference for this value and remember it.
1833 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001834 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001835 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001836 else
1837 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001838
Chris Lattnerdf986172009-01-02 07:01:27 +00001839 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1840 return FwdVal;
1841}
1842
1843/// SetInstName - After an instruction is parsed and inserted into its
1844/// basic block, this installs its name.
1845bool LLParser::PerFunctionState::SetInstName(int NameID,
1846 const std::string &NameStr,
1847 LocTy NameLoc, Instruction *Inst) {
1848 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001849 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001850 if (NameID != -1 || !NameStr.empty())
1851 return P.Error(NameLoc, "instructions returning void cannot have a name");
1852 return false;
1853 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001854
Chris Lattnerdf986172009-01-02 07:01:27 +00001855 // If this was a numbered instruction, verify that the instruction is the
1856 // expected value and resolve any forward references.
1857 if (NameStr.empty()) {
1858 // If neither a name nor an ID was specified, just use the next ID.
1859 if (NameID == -1)
1860 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001861
Chris Lattnerdf986172009-01-02 07:01:27 +00001862 if (unsigned(NameID) != NumberedVals.size())
1863 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001864 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001865
Chris Lattnerdf986172009-01-02 07:01:27 +00001866 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1867 ForwardRefValIDs.find(NameID);
1868 if (FI != ForwardRefValIDs.end()) {
1869 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001870 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001871 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001872 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001873 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001874 ForwardRefValIDs.erase(FI);
1875 }
1876
1877 NumberedVals.push_back(Inst);
1878 return false;
1879 }
1880
1881 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1882 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1883 FI = ForwardRefVals.find(NameStr);
1884 if (FI != ForwardRefVals.end()) {
1885 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001886 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001887 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001888 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001889 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001890 ForwardRefVals.erase(FI);
1891 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001892
Chris Lattnerdf986172009-01-02 07:01:27 +00001893 // Set the name on the instruction.
1894 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001895
Benjamin Krameraf812352010-10-16 11:28:23 +00001896 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001897 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001898 NameStr + "'");
1899 return false;
1900}
1901
1902/// GetBB - Get a basic block with the specified name or ID, creating a
1903/// forward reference record if needed.
1904BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1905 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001906 return cast_or_null<BasicBlock>(GetVal(Name,
1907 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001908}
1909
1910BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001911 return cast_or_null<BasicBlock>(GetVal(ID,
1912 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001913}
1914
1915/// DefineBB - Define the specified basic block, which is either named or
1916/// unnamed. If there is an error, this returns null otherwise it returns
1917/// the block being defined.
1918BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1919 LocTy Loc) {
1920 BasicBlock *BB;
1921 if (Name.empty())
1922 BB = GetBB(NumberedVals.size(), Loc);
1923 else
1924 BB = GetBB(Name, Loc);
1925 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001926
Chris Lattnerdf986172009-01-02 07:01:27 +00001927 // Move the block to the end of the function. Forward ref'd blocks are
1928 // inserted wherever they happen to be referenced.
1929 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001930
Chris Lattnerdf986172009-01-02 07:01:27 +00001931 // Remove the block from forward ref sets.
1932 if (Name.empty()) {
1933 ForwardRefValIDs.erase(NumberedVals.size());
1934 NumberedVals.push_back(BB);
1935 } else {
1936 // BB forward references are already in the function symbol table.
1937 ForwardRefVals.erase(Name);
1938 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001939
Chris Lattnerdf986172009-01-02 07:01:27 +00001940 return BB;
1941}
1942
1943//===----------------------------------------------------------------------===//
1944// Constants.
1945//===----------------------------------------------------------------------===//
1946
1947/// ParseValID - Parse an abstract value that doesn't necessarily have a
1948/// type implied. For example, if we parse "4" we don't know what integer type
1949/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001950/// sanity. PFS is used to convert function-local operands of metadata (since
1951/// metadata operands are not just parsed here but also converted to values).
1952/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001953bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001954 ID.Loc = Lex.getLoc();
1955 switch (Lex.getKind()) {
1956 default: return TokError("expected value token");
1957 case lltok::GlobalID: // @42
1958 ID.UIntVal = Lex.getUIntVal();
1959 ID.Kind = ValID::t_GlobalID;
1960 break;
1961 case lltok::GlobalVar: // @foo
1962 ID.StrVal = Lex.getStrVal();
1963 ID.Kind = ValID::t_GlobalName;
1964 break;
1965 case lltok::LocalVarID: // %42
1966 ID.UIntVal = Lex.getUIntVal();
1967 ID.Kind = ValID::t_LocalID;
1968 break;
1969 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00001970 ID.StrVal = Lex.getStrVal();
1971 ID.Kind = ValID::t_LocalName;
1972 break;
Dan Gohman83448032010-07-14 18:26:50 +00001973 case lltok::exclaim: // !42, !{...}, or !"foo"
1974 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00001975 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001976 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001977 ID.Kind = ValID::t_APSInt;
1978 break;
1979 case lltok::APFloat:
1980 ID.APFloatVal = Lex.getAPFloatVal();
1981 ID.Kind = ValID::t_APFloat;
1982 break;
1983 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001984 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001985 ID.Kind = ValID::t_Constant;
1986 break;
1987 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001988 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001989 ID.Kind = ValID::t_Constant;
1990 break;
1991 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1992 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1993 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001994
Chris Lattnerdf986172009-01-02 07:01:27 +00001995 case lltok::lbrace: {
1996 // ValID ::= '{' ConstVector '}'
1997 Lex.Lex();
1998 SmallVector<Constant*, 16> Elts;
1999 if (ParseGlobalValueVector(Elts) ||
2000 ParseToken(lltok::rbrace, "expected end of struct constant"))
2001 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002002
Chris Lattner1afcace2011-07-09 17:41:24 +00002003 ID.ConstantStructElts = new Constant*[Elts.size()];
2004 ID.UIntVal = Elts.size();
2005 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2006 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002007 return false;
2008 }
2009 case lltok::less: {
2010 // ValID ::= '<' ConstVector '>' --> Vector.
2011 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2012 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002013 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002014
Chris Lattnerdf986172009-01-02 07:01:27 +00002015 SmallVector<Constant*, 16> Elts;
2016 LocTy FirstEltLoc = Lex.getLoc();
2017 if (ParseGlobalValueVector(Elts) ||
2018 (isPackedStruct &&
2019 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2020 ParseToken(lltok::greater, "expected end of constant"))
2021 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002022
Chris Lattnerdf986172009-01-02 07:01:27 +00002023 if (isPackedStruct) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002024 ID.ConstantStructElts = new Constant*[Elts.size()];
2025 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2026 ID.UIntVal = Elts.size();
2027 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002028 return false;
2029 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002030
Chris Lattnerdf986172009-01-02 07:01:27 +00002031 if (Elts.empty())
2032 return Error(ID.Loc, "constant vector must not be empty");
2033
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002034 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002035 !Elts[0]->getType()->isFloatingPointTy() &&
2036 !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002037 return Error(FirstEltLoc,
Nadav Rotem16087692011-12-05 06:29:09 +00002038 "vector elements must have integer, pointer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002039
Chris Lattnerdf986172009-01-02 07:01:27 +00002040 // Verify that all the vector elements have the same type.
2041 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2042 if (Elts[i]->getType() != Elts[0]->getType())
2043 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002044 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002045 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002046
Chris Lattner2ca5c862011-02-15 00:14:00 +00002047 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002048 ID.Kind = ValID::t_Constant;
2049 return false;
2050 }
2051 case lltok::lsquare: { // Array Constant
2052 Lex.Lex();
2053 SmallVector<Constant*, 16> Elts;
2054 LocTy FirstEltLoc = Lex.getLoc();
2055 if (ParseGlobalValueVector(Elts) ||
2056 ParseToken(lltok::rsquare, "expected end of array constant"))
2057 return true;
2058
2059 // Handle empty element.
2060 if (Elts.empty()) {
2061 // Use undef instead of an array because it's inconvenient to determine
2062 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002063 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002064 return false;
2065 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002066
Chris Lattnerdf986172009-01-02 07:01:27 +00002067 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002068 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002069 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002070
Owen Andersondebcb012009-07-29 22:17:13 +00002071 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002072
Chris Lattnerdf986172009-01-02 07:01:27 +00002073 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002074 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002075 if (Elts[i]->getType() != Elts[0]->getType())
2076 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002077 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002078 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00002079 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002080
Jay Foad26701082011-06-22 09:24:39 +00002081 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002082 ID.Kind = ValID::t_Constant;
2083 return false;
2084 }
2085 case lltok::kw_c: // c "foo"
2086 Lex.Lex();
Chris Lattner18c7f802012-02-05 02:29:43 +00002087 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2088 false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002089 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2090 ID.Kind = ValID::t_Constant;
2091 return false;
2092
2093 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002094 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
Chad Rosier581600b2012-09-05 19:00:49 +00002095 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerdf986172009-01-02 07:01:27 +00002096 Lex.Lex();
2097 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002098 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosier581600b2012-09-05 19:00:49 +00002099 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002100 ParseStringConstant(ID.StrVal) ||
2101 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002102 ParseToken(lltok::StringConstant, "expected constraint string"))
2103 return true;
2104 ID.StrVal2 = Lex.getStrVal();
Chad Rosier36547342012-09-05 00:08:17 +00002105 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosier581600b2012-09-05 19:00:49 +00002106 (unsigned(AsmDialect)<<2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002107 ID.Kind = ValID::t_InlineAsm;
2108 return false;
2109 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002110
Chris Lattner09d9ef42009-10-28 03:39:23 +00002111 case lltok::kw_blockaddress: {
2112 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2113 Lex.Lex();
2114
2115 ValID Fn, Label;
2116 LocTy FnLoc, LabelLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00002117
Chris Lattner09d9ef42009-10-28 03:39:23 +00002118 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2119 ParseValID(Fn) ||
2120 ParseToken(lltok::comma, "expected comma in block address expression")||
2121 ParseValID(Label) ||
2122 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2123 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00002124
Chris Lattner09d9ef42009-10-28 03:39:23 +00002125 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2126 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002127 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002128 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman407a6162012-11-15 22:34:00 +00002129
Chris Lattner09d9ef42009-10-28 03:39:23 +00002130 // Make a global variable as a placeholder for this reference.
2131 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2132 false, GlobalValue::InternalLinkage,
2133 0, "");
2134 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2135 ID.ConstantVal = FwdRef;
2136 ID.Kind = ValID::t_Constant;
2137 return false;
2138 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002139
Chris Lattnerdf986172009-01-02 07:01:27 +00002140 case lltok::kw_trunc:
2141 case lltok::kw_zext:
2142 case lltok::kw_sext:
2143 case lltok::kw_fptrunc:
2144 case lltok::kw_fpext:
2145 case lltok::kw_bitcast:
2146 case lltok::kw_uitofp:
2147 case lltok::kw_sitofp:
2148 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002149 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002150 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002151 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002152 unsigned Opc = Lex.getUIntVal();
Chris Lattner1afcace2011-07-09 17:41:24 +00002153 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002154 Constant *SrcVal;
2155 Lex.Lex();
2156 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2157 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002158 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002159 ParseType(DestTy) ||
2160 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2161 return true;
2162 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2163 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002164 getTypeString(SrcVal->getType()) + "' to '" +
2165 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002166 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002167 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002168 ID.Kind = ValID::t_Constant;
2169 return false;
2170 }
2171 case lltok::kw_extractvalue: {
2172 Lex.Lex();
2173 Constant *Val;
2174 SmallVector<unsigned, 4> Indices;
2175 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2176 ParseGlobalTypeAndValue(Val) ||
2177 ParseIndexList(Indices) ||
2178 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2179 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002180
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002181 if (!Val->getType()->isAggregateType())
2182 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002183 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002184 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002185 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002186 ID.Kind = ValID::t_Constant;
2187 return false;
2188 }
2189 case lltok::kw_insertvalue: {
2190 Lex.Lex();
2191 Constant *Val0, *Val1;
2192 SmallVector<unsigned, 4> Indices;
2193 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2194 ParseGlobalTypeAndValue(Val0) ||
2195 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2196 ParseGlobalTypeAndValue(Val1) ||
2197 ParseIndexList(Indices) ||
2198 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2199 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002200 if (!Val0->getType()->isAggregateType())
2201 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002202 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002203 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002204 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002205 ID.Kind = ValID::t_Constant;
2206 return false;
2207 }
2208 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002209 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002210 unsigned PredVal, Opc = Lex.getUIntVal();
2211 Constant *Val0, *Val1;
2212 Lex.Lex();
2213 if (ParseCmpPredicate(PredVal, Opc) ||
2214 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2215 ParseGlobalTypeAndValue(Val0) ||
2216 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2217 ParseGlobalTypeAndValue(Val1) ||
2218 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2219 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002220
Chris Lattnerdf986172009-01-02 07:01:27 +00002221 if (Val0->getType() != Val1->getType())
2222 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002223
Chris Lattnerdf986172009-01-02 07:01:27 +00002224 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002225
Chris Lattnerdf986172009-01-02 07:01:27 +00002226 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002227 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002228 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002229 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002230 } else {
2231 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002232 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002233 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002234 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002235 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002236 }
2237 ID.Kind = ValID::t_Constant;
2238 return false;
2239 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002240
Chris Lattnerdf986172009-01-02 07:01:27 +00002241 // Binary Operators.
2242 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002243 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002244 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002245 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002246 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002247 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002248 case lltok::kw_udiv:
2249 case lltok::kw_sdiv:
2250 case lltok::kw_fdiv:
2251 case lltok::kw_urem:
2252 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002253 case lltok::kw_frem:
2254 case lltok::kw_shl:
2255 case lltok::kw_lshr:
2256 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002257 bool NUW = false;
2258 bool NSW = false;
2259 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002260 unsigned Opc = Lex.getUIntVal();
2261 Constant *Val0, *Val1;
2262 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002263 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002264 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2265 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002266 if (EatIfPresent(lltok::kw_nuw))
2267 NUW = true;
2268 if (EatIfPresent(lltok::kw_nsw)) {
2269 NSW = true;
2270 if (EatIfPresent(lltok::kw_nuw))
2271 NUW = true;
2272 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002273 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2274 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002275 if (EatIfPresent(lltok::kw_exact))
2276 Exact = true;
2277 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002278 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2279 ParseGlobalTypeAndValue(Val0) ||
2280 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2281 ParseGlobalTypeAndValue(Val1) ||
2282 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2283 return true;
2284 if (Val0->getType() != Val1->getType())
2285 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002286 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002287 if (NUW)
2288 return Error(ModifierLoc, "nuw only applies to integer operations");
2289 if (NSW)
2290 return Error(ModifierLoc, "nsw only applies to integer operations");
2291 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002292 // Check that the type is valid for the operator.
2293 switch (Opc) {
2294 case Instruction::Add:
2295 case Instruction::Sub:
2296 case Instruction::Mul:
2297 case Instruction::UDiv:
2298 case Instruction::SDiv:
2299 case Instruction::URem:
2300 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002301 case Instruction::Shl:
2302 case Instruction::AShr:
2303 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002304 if (!Val0->getType()->isIntOrIntVectorTy())
2305 return Error(ID.Loc, "constexpr requires integer operands");
2306 break;
2307 case Instruction::FAdd:
2308 case Instruction::FSub:
2309 case Instruction::FMul:
2310 case Instruction::FDiv:
2311 case Instruction::FRem:
2312 if (!Val0->getType()->isFPOrFPVectorTy())
2313 return Error(ID.Loc, "constexpr requires fp operands");
2314 break;
2315 default: llvm_unreachable("Unknown binary operator!");
2316 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002317 unsigned Flags = 0;
2318 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2319 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002320 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002321 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002322 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002323 ID.Kind = ValID::t_Constant;
2324 return false;
2325 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002326
Chris Lattnerdf986172009-01-02 07:01:27 +00002327 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002328 case lltok::kw_and:
2329 case lltok::kw_or:
2330 case lltok::kw_xor: {
2331 unsigned Opc = Lex.getUIntVal();
2332 Constant *Val0, *Val1;
2333 Lex.Lex();
2334 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2335 ParseGlobalTypeAndValue(Val0) ||
2336 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2337 ParseGlobalTypeAndValue(Val1) ||
2338 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2339 return true;
2340 if (Val0->getType() != Val1->getType())
2341 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002342 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002343 return Error(ID.Loc,
2344 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002345 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002346 ID.Kind = ValID::t_Constant;
2347 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002348 }
2349
Chris Lattnerdf986172009-01-02 07:01:27 +00002350 case lltok::kw_getelementptr:
2351 case lltok::kw_shufflevector:
2352 case lltok::kw_insertelement:
2353 case lltok::kw_extractelement:
2354 case lltok::kw_select: {
2355 unsigned Opc = Lex.getUIntVal();
2356 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002357 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002358 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002359 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002360 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002361 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2362 ParseGlobalValueVector(Elts) ||
2363 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2364 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002365
Chris Lattnerdf986172009-01-02 07:01:27 +00002366 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem16087692011-12-05 06:29:09 +00002367 if (Elts.size() == 0 ||
2368 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002369 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002370
Jay Foaddab3d292011-07-21 14:31:17 +00002371 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foada9203102011-07-25 09:48:08 +00002372 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002373 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad4b5e2072011-07-21 15:15:37 +00002374 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2375 InBounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002376 } else if (Opc == Instruction::Select) {
2377 if (Elts.size() != 3)
2378 return Error(ID.Loc, "expected three operands to select");
2379 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2380 Elts[2]))
2381 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002382 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002383 } else if (Opc == Instruction::ShuffleVector) {
2384 if (Elts.size() != 3)
2385 return Error(ID.Loc, "expected three operands to shufflevector");
2386 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2387 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002388 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002389 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002390 } else if (Opc == Instruction::ExtractElement) {
2391 if (Elts.size() != 2)
2392 return Error(ID.Loc, "expected two operands to extractelement");
2393 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2394 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002395 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002396 } else {
2397 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2398 if (Elts.size() != 3)
2399 return Error(ID.Loc, "expected three operands to insertelement");
2400 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2401 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002402 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002403 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002404 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002405
Chris Lattnerdf986172009-01-02 07:01:27 +00002406 ID.Kind = ValID::t_Constant;
2407 return false;
2408 }
2409 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002410
Chris Lattnerdf986172009-01-02 07:01:27 +00002411 Lex.Lex();
2412 return false;
2413}
2414
2415/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002416bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez92f238d2010-01-11 22:31:58 +00002417 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002418 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002419 Value *V = NULL;
2420 bool Parsed = ParseValID(ID) ||
2421 ConvertValIDToValue(Ty, ID, V, NULL);
2422 if (V && !(C = dyn_cast<Constant>(V)))
2423 return Error(ID.Loc, "global values must be constants");
2424 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002425}
2426
Victor Hernandez92f238d2010-01-11 22:31:58 +00002427bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002428 Type *Ty = 0;
2429 return ParseType(Ty) ||
2430 ParseGlobalValue(Ty, V);
Victor Hernandez92f238d2010-01-11 22:31:58 +00002431}
2432
2433/// ParseGlobalValueVector
2434/// ::= /*empty*/
2435/// ::= TypeAndValue (',' TypeAndValue)*
2436bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2437 // Empty list.
2438 if (Lex.getKind() == lltok::rbrace ||
2439 Lex.getKind() == lltok::rsquare ||
2440 Lex.getKind() == lltok::greater ||
2441 Lex.getKind() == lltok::rparen)
2442 return false;
2443
2444 Constant *C;
2445 if (ParseGlobalTypeAndValue(C)) return true;
2446 Elts.push_back(C);
2447
2448 while (EatIfPresent(lltok::comma)) {
2449 if (ParseGlobalTypeAndValue(C)) return true;
2450 Elts.push_back(C);
2451 }
2452
2453 return false;
2454}
2455
Dan Gohman309b3af2010-08-24 02:24:03 +00002456bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2457 assert(Lex.getKind() == lltok::lbrace);
2458 Lex.Lex();
2459
2460 SmallVector<Value*, 16> Elts;
2461 if (ParseMDNodeVector(Elts, PFS) ||
2462 ParseToken(lltok::rbrace, "expected end of metadata node"))
2463 return true;
2464
Jay Foadec9186b2011-04-21 19:59:31 +00002465 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002466 ID.Kind = ValID::t_MDNode;
2467 return false;
2468}
2469
Dan Gohman83448032010-07-14 18:26:50 +00002470/// ParseMetadataValue
2471/// ::= !42
2472/// ::= !{...}
2473/// ::= !"string"
2474bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2475 assert(Lex.getKind() == lltok::exclaim);
2476 Lex.Lex();
2477
2478 // MDNode:
2479 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002480 if (Lex.getKind() == lltok::lbrace)
2481 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002482
2483 // Standalone metadata reference
2484 // !42
2485 if (Lex.getKind() == lltok::APSInt) {
2486 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2487 ID.Kind = ValID::t_MDNode;
2488 return false;
2489 }
2490
2491 // MDString:
2492 // ::= '!' STRINGCONSTANT
2493 if (ParseMDString(ID.MDStringVal)) return true;
2494 ID.Kind = ValID::t_MDString;
2495 return false;
2496}
2497
Victor Hernandez92f238d2010-01-11 22:31:58 +00002498
2499//===----------------------------------------------------------------------===//
2500// Function Parsing.
2501//===----------------------------------------------------------------------===//
2502
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002503bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez92f238d2010-01-11 22:31:58 +00002504 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002505 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002506 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002507
Chris Lattnerdf986172009-01-02 07:01:27 +00002508 switch (ID.Kind) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002509 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002510 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2511 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2512 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002513 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002514 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2515 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2516 return (V == 0);
2517 case ValID::t_InlineAsm: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002518 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman407a6162012-11-15 22:34:00 +00002519 FunctionType *FTy =
Victor Hernandez92f238d2010-01-11 22:31:58 +00002520 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2521 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2522 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosier36547342012-09-05 00:08:17 +00002523 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosier581600b2012-09-05 19:00:49 +00002524 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez92f238d2010-01-11 22:31:58 +00002525 return false;
2526 }
2527 case ValID::t_MDNode:
2528 if (!Ty->isMetadataTy())
2529 return Error(ID.Loc, "metadata value must have metadata type");
2530 V = ID.MDNodeVal;
2531 return false;
2532 case ValID::t_MDString:
2533 if (!Ty->isMetadataTy())
2534 return Error(ID.Loc, "metadata value must have metadata type");
2535 V = ID.MDStringVal;
2536 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002537 case ValID::t_GlobalName:
2538 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2539 return V == 0;
2540 case ValID::t_GlobalID:
2541 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2542 return V == 0;
2543 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002544 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002545 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002546 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002547 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002548 return false;
2549 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002550 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002551 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2552 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002553
Dan Gohmance163392011-12-17 00:04:22 +00002554 // The lexer has no type info, so builds all half, float, and double FP
2555 // constants as double. Fix this here. Long double does not need this.
2556 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002557 bool Ignored;
Dan Gohmance163392011-12-17 00:04:22 +00002558 if (Ty->isHalfTy())
2559 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2560 &Ignored);
2561 else if (Ty->isFloatTy())
2562 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2563 &Ignored);
Chris Lattnerdf986172009-01-02 07:01:27 +00002564 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002565 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002566
Chris Lattner959873d2009-01-05 18:24:23 +00002567 if (V->getType() != Ty)
2568 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002569 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002570
Chris Lattnerdf986172009-01-02 07:01:27 +00002571 return false;
2572 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002573 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002574 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002575 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002576 return false;
2577 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002578 // FIXME: LabelTy should not be a first-class type.
Chris Lattner1afcace2011-07-09 17:41:24 +00002579 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002580 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002581 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002582 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002583 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002584 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002585 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002586 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002587 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002588 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002589 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002590 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002591 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002592 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002593 return false;
2594 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002595 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002596 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002597
Chris Lattnerdf986172009-01-02 07:01:27 +00002598 V = ID.ConstantVal;
2599 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +00002600 case ValID::t_ConstantStruct:
2601 case ValID::t_PackedConstantStruct:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002602 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002603 if (ST->getNumElements() != ID.UIntVal)
2604 return Error(ID.Loc,
2605 "initializer with struct type has wrong # elements");
2606 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2607 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman407a6162012-11-15 22:34:00 +00002608
Chris Lattner1afcace2011-07-09 17:41:24 +00002609 // Verify that the elements are compatible with the structtype.
2610 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2611 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2612 return Error(ID.Loc, "element " + Twine(i) +
2613 " of struct initializer doesn't match struct element type");
Michael Ilseman407a6162012-11-15 22:34:00 +00002614
Frits van Bommel39b5abf2011-07-18 12:00:32 +00002615 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2616 ID.UIntVal));
Chris Lattner1afcace2011-07-09 17:41:24 +00002617 } else
2618 return Error(ID.Loc, "constant expression type mismatch");
2619 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002620 }
Chandler Carruth732f05c2012-01-10 18:08:01 +00002621 llvm_unreachable("Invalid ValID");
Chris Lattnerdf986172009-01-02 07:01:27 +00002622}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002623
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002624bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002625 V = 0;
2626 ValID ID;
Chris Lattner1afcace2011-07-09 17:41:24 +00002627 return ParseValID(ID, PFS) ||
2628 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002629}
2630
Chris Lattner1afcace2011-07-09 17:41:24 +00002631bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2632 Type *Ty = 0;
2633 return ParseType(Ty) ||
2634 ParseValue(Ty, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002635}
2636
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002637bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2638 PerFunctionState &PFS) {
2639 Value *V;
2640 Loc = Lex.getLoc();
2641 if (ParseTypeAndValue(V, PFS)) return true;
2642 if (!isa<BasicBlock>(V))
2643 return Error(Loc, "expected a basic block");
2644 BB = cast<BasicBlock>(V);
2645 return false;
2646}
2647
2648
Chris Lattnerdf986172009-01-02 07:01:27 +00002649/// FunctionHeader
2650/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002651/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002652/// OptionalAlign OptGC
2653bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2654 // Parse the linkage.
2655 LocTy LinkageLoc = Lex.getLoc();
2656 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002657
Kostya Serebryany164b86b2012-01-20 17:56:17 +00002658 unsigned Visibility;
Bill Wendling702cc912012-10-15 20:35:56 +00002659 AttrBuilder RetAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002660 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00002661 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002662 LocTy RetTypeLoc = Lex.getLoc();
2663 if (ParseOptionalLinkage(Linkage) ||
2664 ParseOptionalVisibility(Visibility) ||
2665 ParseOptionalCallingConv(CC) ||
2666 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002667 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002668 return true;
2669
2670 // Verify that the linkage is ok.
2671 switch ((GlobalValue::LinkageTypes)Linkage) {
2672 case GlobalValue::ExternalLinkage:
2673 break; // always ok.
2674 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002675 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002676 if (isDefine)
2677 return Error(LinkageLoc, "invalid linkage for function definition");
2678 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002679 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002680 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002681 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002682 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002683 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002684 case GlobalValue::LinkOnceAnyLinkage:
2685 case GlobalValue::LinkOnceODRLinkage:
Bill Wendling32811be2012-08-17 18:33:14 +00002686 case GlobalValue::LinkOnceODRAutoHideLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002687 case GlobalValue::WeakAnyLinkage:
2688 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002689 case GlobalValue::DLLExportLinkage:
2690 if (!isDefine)
2691 return Error(LinkageLoc, "invalid linkage for function declaration");
2692 break;
2693 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002694 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002695 return Error(LinkageLoc, "invalid function linkage type");
2696 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002697
Chris Lattner1afcace2011-07-09 17:41:24 +00002698 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002699 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002700
Chris Lattnerdf986172009-01-02 07:01:27 +00002701 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002702
2703 std::string FunctionName;
2704 if (Lex.getKind() == lltok::GlobalVar) {
2705 FunctionName = Lex.getStrVal();
2706 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2707 unsigned NameID = Lex.getUIntVal();
2708
2709 if (NameID != NumberedVals.size())
2710 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002711 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002712 } else {
2713 return TokError("expected function name");
2714 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002715
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002716 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002717
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002718 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002719 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002720
Chris Lattner1afcace2011-07-09 17:41:24 +00002721 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002722 bool isVarArg;
Bill Wendling702cc912012-10-15 20:35:56 +00002723 AttrBuilder FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002724 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002725 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002726 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002727 bool UnnamedAddr;
2728 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002729
Chris Lattner1afcace2011-07-09 17:41:24 +00002730 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002731 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2732 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002733 ParseOptionalAttrs(FuncAttrs, 2) ||
2734 (EatIfPresent(lltok::kw_section) &&
2735 ParseStringConstant(Section)) ||
2736 ParseOptionalAlignment(Alignment) ||
2737 (EatIfPresent(lltok::kw_gc) &&
2738 ParseStringConstant(GC)))
2739 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002740
2741 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingf385f4c2012-10-08 23:27:46 +00002742 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendlingef99fe82012-09-21 15:26:31 +00002743 Alignment = FuncAttrs.getAlignment();
Bill Wendlingdc4efcb2012-10-09 09:17:28 +00002744 FuncAttrs.removeAttribute(Attributes::Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00002745 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002746
Chris Lattnerdf986172009-01-02 07:01:27 +00002747 // Okay, if we got here, the function is syntactically valid. Convert types
2748 // and do semantic checks.
Jay Foad5fdd6c82011-07-12 14:06:48 +00002749 std::vector<Type*> ParamTypeList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002750 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002751
Bill Wendlinge603fe42012-09-19 23:54:18 +00002752 if (RetAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00002753 Attrs.push_back(
2754 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
2755 Attributes::get(RetType->getContext(),
2756 RetAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002757
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002759 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlinge603fe42012-09-19 23:54:18 +00002760 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00002761 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2762 }
2763
Bill Wendlinge603fe42012-09-19 23:54:18 +00002764 if (FuncAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00002765 Attrs.push_back(
2766 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
2767 Attributes::get(RetType->getContext(),
2768 FuncAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00002769
Bill Wendling0976e002012-11-20 05:09:20 +00002770 AttrListPtr PAL = AttrListPtr::get(Context, Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002771
Bill Wendling67658342012-10-09 07:45:08 +00002772 if (PAL.getParamAttributes(1).hasAttribute(Attributes::StructRet) &&
2773 !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002774 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2775
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002776 FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002777 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002778 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002779
2780 Fn = 0;
2781 if (!FunctionName.empty()) {
2782 // If this was a definition of a forward reference, remove the definition
2783 // from the forward reference table and fill in the forward ref.
2784 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2785 ForwardRefVals.find(FunctionName);
2786 if (FRVI != ForwardRefVals.end()) {
2787 Fn = M->getFunction(FunctionName);
Nick Lewycky64ea2752012-10-11 00:38:25 +00002788 if (!Fn)
2789 return Error(FRVI->second.second, "invalid forward reference to "
2790 "function as global value!");
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002791 if (Fn->getType() != PFT)
2792 return Error(FRVI->second.second, "invalid forward reference to "
2793 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman407a6162012-11-15 22:34:00 +00002794
Chris Lattnerdf986172009-01-02 07:01:27 +00002795 ForwardRefVals.erase(FRVI);
2796 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002797 // Reject redefinitions.
2798 return Error(NameLoc, "invalid redefinition of function '" +
2799 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002800 } else if (M->getNamedValue(FunctionName)) {
2801 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002802 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002803
Dan Gohman41905542009-08-29 23:37:49 +00002804 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002805 // If this is a definition of a forward referenced function, make sure the
2806 // types agree.
2807 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2808 = ForwardRefValIDs.find(NumberedVals.size());
2809 if (I != ForwardRefValIDs.end()) {
2810 Fn = cast<Function>(I->second.first);
2811 if (Fn->getType() != PFT)
2812 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002813 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002814 ForwardRefValIDs.erase(I);
2815 }
2816 }
2817
2818 if (Fn == 0)
2819 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2820 else // Move the forward-reference to the correct spot in the module.
2821 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2822
2823 if (FunctionName.empty())
2824 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002825
Chris Lattnerdf986172009-01-02 07:01:27 +00002826 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2827 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2828 Fn->setCallingConv(CC);
2829 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002830 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002831 Fn->setAlignment(Alignment);
2832 Fn->setSection(Section);
2833 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002834
Chris Lattnerdf986172009-01-02 07:01:27 +00002835 // Add all of the arguments we parsed to the function.
2836 Function::arg_iterator ArgIt = Fn->arg_begin();
2837 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2838 // If the argument has a name, insert it into the argument symbol table.
2839 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002840
Chris Lattnerdf986172009-01-02 07:01:27 +00002841 // Set the name, if it conflicted, it will be auto-renamed.
2842 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002843
Benjamin Krameraf812352010-10-16 11:28:23 +00002844 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002845 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2846 ArgList[i].Name + "'");
2847 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002848
Chris Lattnerdf986172009-01-02 07:01:27 +00002849 return false;
2850}
2851
2852
2853/// ParseFunctionBody
2854/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002855///
2856bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002857 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002858 return TokError("expected '{' in function body");
2859 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002860
Chris Lattner09d9ef42009-10-28 03:39:23 +00002861 int FunctionNumber = -1;
2862 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman407a6162012-11-15 22:34:00 +00002863
Chris Lattner09d9ef42009-10-28 03:39:23 +00002864 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002865
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002866 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002867 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002868 return TokError("function body requires at least one basic block");
Michael Ilseman407a6162012-11-15 22:34:00 +00002869
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002870 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002871 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002872
Chris Lattnerdf986172009-01-02 07:01:27 +00002873 // Eat the }.
2874 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002875
Chris Lattnerdf986172009-01-02 07:01:27 +00002876 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002877 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002878}
2879
2880/// ParseBasicBlock
2881/// ::= LabelStr? Instruction*
2882bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2883 // If this basic block starts out with a name, remember it.
2884 std::string Name;
2885 LocTy NameLoc = Lex.getLoc();
2886 if (Lex.getKind() == lltok::LabelStr) {
2887 Name = Lex.getStrVal();
2888 Lex.Lex();
2889 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002890
Chris Lattnerdf986172009-01-02 07:01:27 +00002891 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2892 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002893
Chris Lattnerdf986172009-01-02 07:01:27 +00002894 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002895
Chris Lattnerdf986172009-01-02 07:01:27 +00002896 // Parse the instructions in this block until we get a terminator.
2897 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002898 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002899 do {
2900 // This instruction may have three possibilities for a name: a) none
2901 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2902 LocTy NameLoc = Lex.getLoc();
2903 int NameID = -1;
2904 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002905
Chris Lattnerdf986172009-01-02 07:01:27 +00002906 if (Lex.getKind() == lltok::LocalVarID) {
2907 NameID = Lex.getUIntVal();
2908 Lex.Lex();
2909 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2910 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002911 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002912 NameStr = Lex.getStrVal();
2913 Lex.Lex();
2914 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2915 return true;
2916 }
Devang Patelf633a062009-09-17 23:04:48 +00002917
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002918 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Topper85814382012-02-07 05:05:23 +00002919 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002920 case InstError: return true;
2921 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002922 BB->getInstList().push_back(Inst);
2923
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002924 // With a normal result, we check to see if the instruction is followed by
2925 // a comma and metadata.
2926 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002927 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002928 return true;
2929 break;
2930 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002931 BB->getInstList().push_back(Inst);
2932
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002933 // If the instruction parser ate an extra comma at the end of it, it
2934 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002935 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002936 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00002937 break;
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002938 }
Devang Patelf633a062009-09-17 23:04:48 +00002939
Chris Lattnerdf986172009-01-02 07:01:27 +00002940 // Set the name on the instruction.
2941 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2942 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002943
Chris Lattnerdf986172009-01-02 07:01:27 +00002944 return false;
2945}
2946
2947//===----------------------------------------------------------------------===//
2948// Instruction Parsing.
2949//===----------------------------------------------------------------------===//
2950
2951/// ParseInstruction - Parse one of the many different instructions.
2952///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002953int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2954 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002955 lltok::Kind Token = Lex.getKind();
2956 if (Token == lltok::Eof)
2957 return TokError("found end of file when expecting more instructions");
2958 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002959 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002960 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002961
Chris Lattnerdf986172009-01-02 07:01:27 +00002962 switch (Token) {
2963 default: return Error(Loc, "expected instruction opcode");
2964 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002965 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002966 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2967 case lltok::kw_br: return ParseBr(Inst, PFS);
2968 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002969 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002970 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002971 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002972 // Binary Operators.
2973 case lltok::kw_add:
2974 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00002975 case lltok::kw_mul:
2976 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00002977 bool NUW = EatIfPresent(lltok::kw_nuw);
2978 bool NSW = EatIfPresent(lltok::kw_nsw);
2979 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman407a6162012-11-15 22:34:00 +00002980
Chris Lattnerf067d582011-02-07 16:40:21 +00002981 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00002982
Chris Lattnerf067d582011-02-07 16:40:21 +00002983 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2984 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2985 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002986 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002987 case lltok::kw_fadd:
2988 case lltok::kw_fsub:
Michael Ilseman15c13d32012-11-27 00:42:44 +00002989 case lltok::kw_fmul:
2990 case lltok::kw_fdiv:
2991 case lltok::kw_frem: {
2992 FastMathFlags FMF = EatFastMathFlagsIfPresent();
2993 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
2994 if (Res != 0)
2995 return Res;
2996 if (FMF.any())
2997 Inst->setFastMathFlags(FMF);
2998 return 0;
2999 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003000
Chris Lattner35bda892011-02-06 21:44:57 +00003001 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00003002 case lltok::kw_udiv:
3003 case lltok::kw_lshr:
3004 case lltok::kw_ashr: {
3005 bool Exact = EatIfPresent(lltok::kw_exact);
3006
3007 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3008 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3009 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00003010 }
3011
Chris Lattnerdf986172009-01-02 07:01:27 +00003012 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003013 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003014 case lltok::kw_and:
3015 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003016 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003017 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003018 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003019 // Casts.
3020 case lltok::kw_trunc:
3021 case lltok::kw_zext:
3022 case lltok::kw_sext:
3023 case lltok::kw_fptrunc:
3024 case lltok::kw_fpext:
3025 case lltok::kw_bitcast:
3026 case lltok::kw_uitofp:
3027 case lltok::kw_sitofp:
3028 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003029 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003030 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003031 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003032 // Other.
3033 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003034 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003035 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3036 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3037 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3038 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlinge6e88262011-08-12 20:24:12 +00003039 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003040 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3041 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3042 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003043 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003044 case lltok::kw_load: return ParseLoad(Inst, PFS);
3045 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedmanf03bb262011-08-12 22:50:01 +00003046 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3047 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedman47f35132011-07-25 23:16:38 +00003048 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003049 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3050 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3051 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3052 }
3053}
3054
3055/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3056bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003057 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003058 switch (Lex.getKind()) {
3059 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3060 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3061 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3062 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3063 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3064 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3065 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3066 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3067 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3068 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3069 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3070 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3071 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3072 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3073 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3074 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3075 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3076 }
3077 } else {
3078 switch (Lex.getKind()) {
3079 default: TokError("expected icmp predicate (e.g. 'eq')");
3080 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3081 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3082 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3083 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3084 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3085 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3086 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3087 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3088 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3089 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3090 }
3091 }
3092 Lex.Lex();
3093 return false;
3094}
3095
3096//===----------------------------------------------------------------------===//
3097// Terminator Instructions.
3098//===----------------------------------------------------------------------===//
3099
3100/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003101/// ::= 'ret' void (',' !dbg, !1)*
3102/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003103bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattner1afcace2011-07-09 17:41:24 +00003104 PerFunctionState &PFS) {
3105 SMLoc TypeLoc = Lex.getLoc();
3106 Type *Ty = 0;
Chris Lattnera9a9e072009-03-09 04:49:14 +00003107 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003108
Chris Lattner1afcace2011-07-09 17:41:24 +00003109 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman407a6162012-11-15 22:34:00 +00003110
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003111 if (Ty->isVoidTy()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003112 if (!ResType->isVoidTy())
3113 return Error(TypeLoc, "value doesn't match function result type '" +
3114 getTypeString(ResType) + "'");
Michael Ilseman407a6162012-11-15 22:34:00 +00003115
Owen Anderson1d0be152009-08-13 21:58:54 +00003116 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003117 return false;
3118 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003119
Chris Lattnerdf986172009-01-02 07:01:27 +00003120 Value *RV;
3121 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003122
Chris Lattner1afcace2011-07-09 17:41:24 +00003123 if (ResType != RV->getType())
3124 return Error(TypeLoc, "value doesn't match function result type '" +
3125 getTypeString(ResType) + "'");
Michael Ilseman407a6162012-11-15 22:34:00 +00003126
Owen Anderson1d0be152009-08-13 21:58:54 +00003127 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003128 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003129}
3130
3131
3132/// ParseBr
3133/// ::= 'br' TypeAndValue
3134/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3135bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3136 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003137 Value *Op0;
3138 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003139 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003140
Chris Lattnerdf986172009-01-02 07:01:27 +00003141 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3142 Inst = BranchInst::Create(BB);
3143 return false;
3144 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003145
Owen Anderson1d0be152009-08-13 21:58:54 +00003146 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003147 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003148
Chris Lattnerdf986172009-01-02 07:01:27 +00003149 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003150 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003151 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003152 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003153 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003154
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003155 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003156 return false;
3157}
3158
3159/// ParseSwitch
3160/// Instruction
3161/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3162/// JumpTable
3163/// ::= (TypeAndValue ',' TypeAndValue)*
3164bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3165 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003166 Value *Cond;
3167 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003168 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3169 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003170 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003171 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3172 return true;
3173
Duncan Sands1df98592010-02-16 11:11:14 +00003174 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003175 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003176
Chris Lattnerdf986172009-01-02 07:01:27 +00003177 // Parse the jump table pairs.
3178 SmallPtrSet<Value*, 32> SeenCases;
3179 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3180 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003181 Value *Constant;
3182 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003183
Chris Lattnerdf986172009-01-02 07:01:27 +00003184 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3185 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003186 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003187 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003188
Chris Lattnerdf986172009-01-02 07:01:27 +00003189 if (!SeenCases.insert(Constant))
3190 return Error(CondLoc, "duplicate case value in switch");
3191 if (!isa<ConstantInt>(Constant))
3192 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003193
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003194 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003195 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003196
Chris Lattnerdf986172009-01-02 07:01:27 +00003197 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003198
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003199 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003200 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3201 SI->addCase(Table[i].first, Table[i].second);
3202 Inst = SI;
3203 return false;
3204}
3205
Chris Lattnerab21db72009-10-28 00:19:10 +00003206/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003207/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003208/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3209bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003210 LocTy AddrLoc;
3211 Value *Address;
3212 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003213 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3214 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003215 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00003216
Duncan Sands1df98592010-02-16 11:11:14 +00003217 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003218 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman407a6162012-11-15 22:34:00 +00003219
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003220 // Parse the destination list.
3221 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman407a6162012-11-15 22:34:00 +00003222
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003223 if (Lex.getKind() != lltok::rsquare) {
3224 BasicBlock *DestBB;
3225 if (ParseTypeAndBasicBlock(DestBB, PFS))
3226 return true;
3227 DestList.push_back(DestBB);
Michael Ilseman407a6162012-11-15 22:34:00 +00003228
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003229 while (EatIfPresent(lltok::comma)) {
3230 if (ParseTypeAndBasicBlock(DestBB, PFS))
3231 return true;
3232 DestList.push_back(DestBB);
3233 }
3234 }
Michael Ilseman407a6162012-11-15 22:34:00 +00003235
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003236 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3237 return true;
3238
Chris Lattnerab21db72009-10-28 00:19:10 +00003239 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003240 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3241 IBI->addDestination(DestList[i]);
3242 Inst = IBI;
3243 return false;
3244}
3245
3246
Chris Lattnerdf986172009-01-02 07:01:27 +00003247/// ParseInvoke
3248/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3249/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3250bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3251 LocTy CallLoc = Lex.getLoc();
Bill Wendling702cc912012-10-15 20:35:56 +00003252 AttrBuilder RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003253 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003254 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003255 LocTy RetTypeLoc;
3256 ValID CalleeID;
3257 SmallVector<ParamInfo, 16> ArgList;
3258
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003259 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003260 if (ParseOptionalCallingConv(CC) ||
3261 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003262 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003263 ParseValID(CalleeID) ||
3264 ParseParameterList(ArgList, PFS) ||
3265 ParseOptionalAttrs(FnAttrs, 2) ||
3266 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003267 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003268 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003269 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003270 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003271
Chris Lattnerdf986172009-01-02 07:01:27 +00003272 // If RetType is a non-function pointer type, then this is the short syntax
3273 // for the call, which means that RetType is just the return type. Infer the
3274 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003275 PointerType *PFTy = 0;
3276 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003277 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3278 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3279 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003280 std::vector<Type*> ParamTypes;
Chris Lattnerdf986172009-01-02 07:01:27 +00003281 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3282 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003283
Chris Lattnerdf986172009-01-02 07:01:27 +00003284 if (!FunctionType::isValidReturnType(RetType))
3285 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003286
Owen Andersondebcb012009-07-29 22:17:13 +00003287 Ty = FunctionType::get(RetType, ParamTypes, false);
3288 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003289 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003290
Chris Lattnerdf986172009-01-02 07:01:27 +00003291 // Look up the callee.
3292 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003293 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003294
Chris Lattnerdf986172009-01-02 07:01:27 +00003295 // Set up the Attributes for the function.
3296 SmallVector<AttributeWithIndex, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003297 if (RetAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003298 Attrs.push_back(
3299 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
3300 Attributes::get(Callee->getContext(),
3301 RetAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003302
Chris Lattnerdf986172009-01-02 07:01:27 +00003303 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003304
Chris Lattnerdf986172009-01-02 07:01:27 +00003305 // Loop through FunctionType's arguments and ensure they are specified
3306 // correctly. Also, gather any parameter attributes.
3307 FunctionType::param_iterator I = Ty->param_begin();
3308 FunctionType::param_iterator E = Ty->param_end();
3309 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003310 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003311 if (I != E) {
3312 ExpectedTy = *I++;
3313 } else if (!Ty->isVarArg()) {
3314 return Error(ArgList[i].Loc, "too many arguments specified");
3315 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003316
Chris Lattnerdf986172009-01-02 07:01:27 +00003317 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3318 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003319 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003320 Args.push_back(ArgList[i].V);
Bill Wendlinge603fe42012-09-19 23:54:18 +00003321 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003322 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3323 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003324
Chris Lattnerdf986172009-01-02 07:01:27 +00003325 if (I != E)
3326 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003327
Bill Wendlinge603fe42012-09-19 23:54:18 +00003328 if (FnAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003329 Attrs.push_back(
3330 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
3331 Attributes::get(Callee->getContext(),
3332 FnAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003333
Chris Lattnerdf986172009-01-02 07:01:27 +00003334 // Finish off the Attributes and check them
Bill Wendling0976e002012-11-20 05:09:20 +00003335 AttrListPtr PAL = AttrListPtr::get(Context, Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003336
Jay Foada3efbb12011-07-15 08:37:34 +00003337 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003338 II->setCallingConv(CC);
3339 II->setAttributes(PAL);
3340 Inst = II;
3341 return false;
3342}
3343
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003344/// ParseResume
3345/// ::= 'resume' TypeAndValue
3346bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3347 Value *Exn; LocTy ExnLoc;
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003348 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3349 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003350
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003351 ResumeInst *RI = ResumeInst::Create(Exn);
3352 Inst = RI;
3353 return false;
3354}
Chris Lattnerdf986172009-01-02 07:01:27 +00003355
3356//===----------------------------------------------------------------------===//
3357// Binary Operators.
3358//===----------------------------------------------------------------------===//
3359
3360/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003361/// ::= ArithmeticOps TypeAndValue ',' Value
3362///
3363/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3364/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003365bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003366 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003367 LocTy Loc; Value *LHS, *RHS;
3368 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3369 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3370 ParseValue(LHS->getType(), RHS, PFS))
3371 return true;
3372
Chris Lattnere914b592009-01-05 08:24:46 +00003373 bool Valid;
3374 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003375 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003376 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003377 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3378 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003379 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003380 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3381 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003382 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003383
Chris Lattnere914b592009-01-05 08:24:46 +00003384 if (!Valid)
3385 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003386
Chris Lattnerdf986172009-01-02 07:01:27 +00003387 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3388 return false;
3389}
3390
3391/// ParseLogical
3392/// ::= ArithmeticOps TypeAndValue ',' Value {
3393bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3394 unsigned Opc) {
3395 LocTy Loc; Value *LHS, *RHS;
3396 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3397 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3398 ParseValue(LHS->getType(), RHS, PFS))
3399 return true;
3400
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003401 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003402 return Error(Loc,"instruction requires integer or integer vector operands");
3403
3404 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3405 return false;
3406}
3407
3408
3409/// ParseCompare
3410/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3411/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003412bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3413 unsigned Opc) {
3414 // Parse the integer/fp comparison predicate.
3415 LocTy Loc;
3416 unsigned Pred;
3417 Value *LHS, *RHS;
3418 if (ParseCmpPredicate(Pred, Opc) ||
3419 ParseTypeAndValue(LHS, Loc, PFS) ||
3420 ParseToken(lltok::comma, "expected ',' after compare value") ||
3421 ParseValue(LHS->getType(), RHS, PFS))
3422 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003423
Chris Lattnerdf986172009-01-02 07:01:27 +00003424 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003425 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003426 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003427 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003428 } else {
3429 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003430 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00003431 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003432 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003433 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003434 }
3435 return false;
3436}
3437
3438//===----------------------------------------------------------------------===//
3439// Other Instructions.
3440//===----------------------------------------------------------------------===//
3441
3442
3443/// ParseCast
3444/// ::= CastOpc TypeAndValue 'to' Type
3445bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3446 unsigned Opc) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003447 LocTy Loc;
3448 Value *Op;
3449 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003450 if (ParseTypeAndValue(Op, Loc, PFS) ||
3451 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3452 ParseType(DestTy))
3453 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003454
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003455 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3456 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003457 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003458 getTypeString(Op->getType()) + "' to '" +
3459 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003460 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003461 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3462 return false;
3463}
3464
3465/// ParseSelect
3466/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3467bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3468 LocTy Loc;
3469 Value *Op0, *Op1, *Op2;
3470 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3471 ParseToken(lltok::comma, "expected ',' after select condition") ||
3472 ParseTypeAndValue(Op1, PFS) ||
3473 ParseToken(lltok::comma, "expected ',' after select value") ||
3474 ParseTypeAndValue(Op2, PFS))
3475 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003476
Chris Lattnerdf986172009-01-02 07:01:27 +00003477 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3478 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003479
Chris Lattnerdf986172009-01-02 07:01:27 +00003480 Inst = SelectInst::Create(Op0, Op1, Op2);
3481 return false;
3482}
3483
Chris Lattner0088a5c2009-01-05 08:18:44 +00003484/// ParseVA_Arg
3485/// ::= 'va_arg' TypeAndValue ',' Type
3486bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003487 Value *Op;
Chris Lattner1afcace2011-07-09 17:41:24 +00003488 Type *EltTy = 0;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003489 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003490 if (ParseTypeAndValue(Op, PFS) ||
3491 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003492 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003493 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003494
Chris Lattner0088a5c2009-01-05 08:18:44 +00003495 if (!EltTy->isFirstClassType())
3496 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003497
3498 Inst = new VAArgInst(Op, EltTy);
3499 return false;
3500}
3501
3502/// ParseExtractElement
3503/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3504bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3505 LocTy Loc;
3506 Value *Op0, *Op1;
3507 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3508 ParseToken(lltok::comma, "expected ',' after extract value") ||
3509 ParseTypeAndValue(Op1, PFS))
3510 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003511
Chris Lattnerdf986172009-01-02 07:01:27 +00003512 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3513 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003514
Eric Christophera3500da2009-07-25 02:28:41 +00003515 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003516 return false;
3517}
3518
3519/// ParseInsertElement
3520/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3521bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3522 LocTy Loc;
3523 Value *Op0, *Op1, *Op2;
3524 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3525 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3526 ParseTypeAndValue(Op1, PFS) ||
3527 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3528 ParseTypeAndValue(Op2, PFS))
3529 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003530
Chris Lattnerdf986172009-01-02 07:01:27 +00003531 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003532 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003533
Chris Lattnerdf986172009-01-02 07:01:27 +00003534 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3535 return false;
3536}
3537
3538/// ParseShuffleVector
3539/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3540bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3541 LocTy Loc;
3542 Value *Op0, *Op1, *Op2;
3543 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3544 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3545 ParseTypeAndValue(Op1, PFS) ||
3546 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3547 ParseTypeAndValue(Op2, PFS))
3548 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003549
Chris Lattnerdf986172009-01-02 07:01:27 +00003550 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperaf393682012-02-01 23:43:12 +00003551 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003552
Chris Lattnerdf986172009-01-02 07:01:27 +00003553 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3554 return false;
3555}
3556
3557/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003558/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003559int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003560 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003561 Value *Op0, *Op1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003562
Chris Lattner1afcace2011-07-09 17:41:24 +00003563 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003564 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3565 ParseValue(Ty, Op0, PFS) ||
3566 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003567 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003568 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3569 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003570
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003571 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003572 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3573 while (1) {
3574 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003575
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003576 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003577 break;
3578
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003579 if (Lex.getKind() == lltok::MetadataVar) {
3580 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003581 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003582 }
Devang Patela43d46f2009-10-16 18:45:49 +00003583
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003584 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003585 ParseValue(Ty, Op0, PFS) ||
3586 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003587 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003588 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3589 return true;
3590 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003591
Chris Lattnerdf986172009-01-02 07:01:27 +00003592 if (!Ty->isFirstClassType())
3593 return Error(TypeLoc, "phi node must have first class type");
3594
Jay Foad3ecfc862011-03-30 11:28:46 +00003595 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003596 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3597 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3598 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003599 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003600}
3601
Bill Wendlinge6e88262011-08-12 20:24:12 +00003602/// ParseLandingPad
3603/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3604/// Clause
3605/// ::= 'catch' TypeAndValue
3606/// ::= 'filter'
3607/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3608bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3609 Type *Ty = 0; LocTy TyLoc;
3610 Value *PersFn; LocTy PersFnLoc;
Bill Wendlinge6e88262011-08-12 20:24:12 +00003611
3612 if (ParseType(Ty, TyLoc) ||
3613 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3614 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3615 return true;
3616
3617 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3618 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3619
3620 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3621 LandingPadInst::ClauseType CT;
3622 if (EatIfPresent(lltok::kw_catch))
3623 CT = LandingPadInst::Catch;
3624 else if (EatIfPresent(lltok::kw_filter))
3625 CT = LandingPadInst::Filter;
3626 else
3627 return TokError("expected 'catch' or 'filter' clause type");
3628
3629 Value *V; LocTy VLoc;
3630 if (ParseTypeAndValue(V, VLoc, PFS)) {
3631 delete LP;
3632 return true;
3633 }
3634
Bill Wendling746c8822011-08-12 20:52:25 +00003635 // A 'catch' type expects a non-array constant. A filter clause expects an
3636 // array constant.
3637 if (CT == LandingPadInst::Catch) {
3638 if (isa<ArrayType>(V->getType()))
3639 Error(VLoc, "'catch' clause has an invalid type");
3640 } else {
3641 if (!isa<ArrayType>(V->getType()))
3642 Error(VLoc, "'filter' clause has an invalid type");
3643 }
3644
Bill Wendlinge6e88262011-08-12 20:24:12 +00003645 LP->addClause(V);
3646 }
3647
3648 Inst = LP;
3649 return false;
3650}
3651
Chris Lattnerdf986172009-01-02 07:01:27 +00003652/// ParseCall
3653/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3654/// ParameterList OptionalAttrs
3655bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3656 bool isTail) {
Bill Wendling702cc912012-10-15 20:35:56 +00003657 AttrBuilder RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003658 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003659 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003660 LocTy RetTypeLoc;
3661 ValID CalleeID;
3662 SmallVector<ParamInfo, 16> ArgList;
3663 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003664
Chris Lattnerdf986172009-01-02 07:01:27 +00003665 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3666 ParseOptionalCallingConv(CC) ||
3667 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003668 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003669 ParseValID(CalleeID) ||
3670 ParseParameterList(ArgList, PFS) ||
3671 ParseOptionalAttrs(FnAttrs, 2))
3672 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003673
Chris Lattnerdf986172009-01-02 07:01:27 +00003674 // If RetType is a non-function pointer type, then this is the short syntax
3675 // for the call, which means that RetType is just the return type. Infer the
3676 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003677 PointerType *PFTy = 0;
3678 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003679 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3680 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3681 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003682 std::vector<Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003683 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3684 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003685
Chris Lattnerdf986172009-01-02 07:01:27 +00003686 if (!FunctionType::isValidReturnType(RetType))
3687 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003688
Owen Andersondebcb012009-07-29 22:17:13 +00003689 Ty = FunctionType::get(RetType, ParamTypes, false);
3690 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003691 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003692
Chris Lattnerdf986172009-01-02 07:01:27 +00003693 // Look up the callee.
3694 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003695 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003696
Chris Lattnerdf986172009-01-02 07:01:27 +00003697 // Set up the Attributes for the function.
3698 SmallVector<AttributeWithIndex, 8> Attrs;
Bill Wendlinge603fe42012-09-19 23:54:18 +00003699 if (RetAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003700 Attrs.push_back(
3701 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
3702 Attributes::get(Callee->getContext(),
3703 RetAttrs)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003704
Chris Lattnerdf986172009-01-02 07:01:27 +00003705 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003706
Chris Lattnerdf986172009-01-02 07:01:27 +00003707 // Loop through FunctionType's arguments and ensure they are specified
3708 // correctly. Also, gather any parameter attributes.
3709 FunctionType::param_iterator I = Ty->param_begin();
3710 FunctionType::param_iterator E = Ty->param_end();
3711 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003712 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003713 if (I != E) {
3714 ExpectedTy = *I++;
3715 } else if (!Ty->isVarArg()) {
3716 return Error(ArgList[i].Loc, "too many arguments specified");
3717 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003718
Chris Lattnerdf986172009-01-02 07:01:27 +00003719 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3720 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003721 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003722 Args.push_back(ArgList[i].V);
Bill Wendlinge603fe42012-09-19 23:54:18 +00003723 if (ArgList[i].Attrs.hasAttributes())
Chris Lattnerdf986172009-01-02 07:01:27 +00003724 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3725 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003726
Chris Lattnerdf986172009-01-02 07:01:27 +00003727 if (I != E)
3728 return Error(CallLoc, "not enough parameters specified for call");
3729
Bill Wendlinge603fe42012-09-19 23:54:18 +00003730 if (FnAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00003731 Attrs.push_back(
3732 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
3733 Attributes::get(Callee->getContext(),
3734 FnAttrs)));
Chris Lattnerdf986172009-01-02 07:01:27 +00003735
3736 // Finish off the Attributes and check them
Bill Wendling0976e002012-11-20 05:09:20 +00003737 AttrListPtr PAL = AttrListPtr::get(Context, Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003738
Jay Foada3efbb12011-07-15 08:37:34 +00003739 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003740 CI->setTailCall(isTail);
3741 CI->setCallingConv(CC);
3742 CI->setAttributes(PAL);
3743 Inst = CI;
3744 return false;
3745}
3746
3747//===----------------------------------------------------------------------===//
3748// Memory Instructions.
3749//===----------------------------------------------------------------------===//
3750
3751/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003752/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003753int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003754 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003755 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003756 unsigned Alignment = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00003757 Type *Ty = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003758 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003759
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003760 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003761 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003762 if (Lex.getKind() == lltok::kw_align) {
3763 if (ParseOptionalAlignment(Alignment)) return true;
3764 } else if (Lex.getKind() == lltok::MetadataVar) {
3765 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003766 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003767 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3768 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3769 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003770 }
3771 }
3772
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003773 if (Size && !Size->getType()->isIntegerTy())
3774 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003775
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003776 Inst = new AllocaInst(Ty, Size, Alignment);
3777 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003778}
3779
3780/// ParseLoad
Eli Friedmanf03bb262011-08-12 22:50:01 +00003781/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman407a6162012-11-15 22:34:00 +00003782/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedmanf03bb262011-08-12 22:50:01 +00003783/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003784int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003785 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003786 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003787 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003788 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003789 AtomicOrdering Ordering = NotAtomic;
3790 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003791
3792 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003793 isAtomic = true;
3794 Lex.Lex();
3795 }
3796
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003797 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003798 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003799 isVolatile = true;
3800 Lex.Lex();
3801 }
3802
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003803 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003804 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003805 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3806 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003807
Duncan Sands1df98592010-02-16 11:11:14 +00003808 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003809 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3810 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman21006d42011-08-09 23:02:53 +00003811 if (isAtomic && !Alignment)
3812 return Error(Loc, "atomic load must have explicit non-zero alignment");
3813 if (Ordering == Release || Ordering == AcquireRelease)
3814 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003815
Eli Friedman21006d42011-08-09 23:02:53 +00003816 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003817 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003818}
3819
3820/// ParseStore
Eli Friedmanf03bb262011-08-12 22:50:01 +00003821
3822/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3823/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman21006d42011-08-09 23:02:53 +00003824/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003825int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003826 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003827 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003828 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003829 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003830 AtomicOrdering Ordering = NotAtomic;
3831 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003832
3833 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003834 isAtomic = true;
3835 Lex.Lex();
3836 }
3837
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003838 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003839 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003840 isVolatile = true;
3841 Lex.Lex();
3842 }
3843
Chris Lattnerdf986172009-01-02 07:01:27 +00003844 if (ParseTypeAndValue(Val, Loc, PFS) ||
3845 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003846 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003847 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003848 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003849 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003850
Duncan Sands1df98592010-02-16 11:11:14 +00003851 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003852 return Error(PtrLoc, "store operand must be a pointer");
3853 if (!Val->getType()->isFirstClassType())
3854 return Error(Loc, "store operand must be a first class value");
3855 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3856 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman21006d42011-08-09 23:02:53 +00003857 if (isAtomic && !Alignment)
3858 return Error(Loc, "atomic store must have explicit non-zero alignment");
3859 if (Ordering == Acquire || Ordering == AcquireRelease)
3860 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003861
Eli Friedman21006d42011-08-09 23:02:53 +00003862 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003863 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003864}
3865
Eli Friedmanff030482011-07-28 21:48:00 +00003866/// ParseCmpXchg
Eli Friedmanf03bb262011-08-12 22:50:01 +00003867/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3868/// 'singlethread'? AtomicOrdering
3869int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003870 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3871 bool AteExtraComma = false;
3872 AtomicOrdering Ordering = NotAtomic;
3873 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003874 bool isVolatile = false;
3875
3876 if (EatIfPresent(lltok::kw_volatile))
3877 isVolatile = true;
3878
Eli Friedmanff030482011-07-28 21:48:00 +00003879 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3880 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3881 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3882 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3883 ParseTypeAndValue(New, NewLoc, PFS) ||
3884 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3885 return true;
3886
3887 if (Ordering == Unordered)
3888 return TokError("cmpxchg cannot be unordered");
3889 if (!Ptr->getType()->isPointerTy())
3890 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3891 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3892 return Error(CmpLoc, "compare value and pointer type do not match");
3893 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3894 return Error(NewLoc, "new value and pointer type do not match");
3895 if (!New->getType()->isIntegerTy())
3896 return Error(NewLoc, "cmpxchg operand must be an integer");
3897 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3898 if (Size < 8 || (Size & (Size - 1)))
3899 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3900 " integer");
3901
3902 AtomicCmpXchgInst *CXI =
3903 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3904 CXI->setVolatile(isVolatile);
3905 Inst = CXI;
3906 return AteExtraComma ? InstExtraComma : InstNormal;
3907}
3908
3909/// ParseAtomicRMW
Eli Friedmanf03bb262011-08-12 22:50:01 +00003910/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3911/// 'singlethread'? AtomicOrdering
3912int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003913 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3914 bool AteExtraComma = false;
3915 AtomicOrdering Ordering = NotAtomic;
3916 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003917 bool isVolatile = false;
Eli Friedmanff030482011-07-28 21:48:00 +00003918 AtomicRMWInst::BinOp Operation;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003919
3920 if (EatIfPresent(lltok::kw_volatile))
3921 isVolatile = true;
3922
Eli Friedmanff030482011-07-28 21:48:00 +00003923 switch (Lex.getKind()) {
3924 default: return TokError("expected binary operation in atomicrmw");
3925 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3926 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3927 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3928 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3929 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3930 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3931 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3932 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3933 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3934 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3935 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3936 }
3937 Lex.Lex(); // Eat the operation.
3938
3939 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3940 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3941 ParseTypeAndValue(Val, ValLoc, PFS) ||
3942 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3943 return true;
3944
3945 if (Ordering == Unordered)
3946 return TokError("atomicrmw cannot be unordered");
3947 if (!Ptr->getType()->isPointerTy())
3948 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3949 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3950 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3951 if (!Val->getType()->isIntegerTy())
3952 return Error(ValLoc, "atomicrmw operand must be an integer");
3953 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3954 if (Size < 8 || (Size & (Size - 1)))
3955 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3956 " integer");
3957
3958 AtomicRMWInst *RMWI =
3959 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3960 RMWI->setVolatile(isVolatile);
3961 Inst = RMWI;
3962 return AteExtraComma ? InstExtraComma : InstNormal;
3963}
3964
Eli Friedman47f35132011-07-25 23:16:38 +00003965/// ParseFence
3966/// ::= 'fence' 'singlethread'? AtomicOrdering
3967int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3968 AtomicOrdering Ordering = NotAtomic;
3969 SynchronizationScope Scope = CrossThread;
3970 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3971 return true;
3972
3973 if (Ordering == Unordered)
3974 return TokError("fence cannot be unordered");
3975 if (Ordering == Monotonic)
3976 return TokError("fence cannot be monotonic");
3977
3978 Inst = new FenceInst(Context, Ordering, Scope);
3979 return InstNormal;
3980}
3981
Chris Lattnerdf986172009-01-02 07:01:27 +00003982/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003983/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003984int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Nadav Rotem16087692011-12-05 06:29:09 +00003985 Value *Ptr = 0;
3986 Value *Val = 0;
3987 LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003988
Dan Gohmandcb40a32009-07-29 15:58:36 +00003989 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003990
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003991 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003992
Nadav Rotem16087692011-12-05 06:29:09 +00003993 if (!Ptr->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003994 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003995
Chris Lattnerdf986172009-01-02 07:01:27 +00003996 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003997 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003998 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003999 if (Lex.getKind() == lltok::MetadataVar) {
4000 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00004001 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004002 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00004003 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem16087692011-12-05 06:29:09 +00004004 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00004005 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem16087692011-12-05 06:29:09 +00004006 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4007 return Error(EltLoc, "getelementptr index type missmatch");
4008 if (Val->getType()->isVectorTy()) {
4009 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4010 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4011 if (ValNumEl != PtrNumEl)
4012 return Error(EltLoc,
4013 "getelementptr vector index has a wrong number of elements");
4014 }
Chris Lattnerdf986172009-01-02 07:01:27 +00004015 Indices.push_back(Val);
4016 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00004017
Jay Foada9203102011-07-25 09:48:08 +00004018 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004019 return Error(Loc, "invalid getelementptr indices");
Jay Foada9203102011-07-25 09:48:08 +00004020 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohmandd8004d2009-07-27 21:53:46 +00004021 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004022 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004023 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004024}
4025
4026/// ParseExtractValue
4027/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004028int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004029 Value *Val; LocTy Loc;
4030 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004031 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004032 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004033 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004034 return true;
4035
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004036 if (!Val->getType()->isAggregateType())
4037 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00004038
Jay Foadfc6d3a42011-07-13 10:26:04 +00004039 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004040 return Error(Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004041 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004042 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004043}
4044
4045/// ParseInsertValue
4046/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004047int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00004048 Value *Val0, *Val1; LocTy Loc0, Loc1;
4049 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004050 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00004051 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4052 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4053 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004054 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004055 return true;
Michael Ilseman407a6162012-11-15 22:34:00 +00004056
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004057 if (!Val0->getType()->isAggregateType())
4058 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004059
Jay Foadfc6d3a42011-07-13 10:26:04 +00004060 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004061 return Error(Loc0, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004062 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004063 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004064}
Nick Lewycky21cc4462009-04-04 07:22:01 +00004065
4066//===----------------------------------------------------------------------===//
4067// Embedded metadata.
4068//===----------------------------------------------------------------------===//
4069
4070/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00004071/// ::= Element (',' Element)*
4072/// Element
4073/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00004074bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00004075 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00004076 // Check for an empty list.
4077 if (Lex.getKind() == lltok::rbrace)
4078 return false;
4079
Nick Lewycky21cc4462009-04-04 07:22:01 +00004080 do {
Chris Lattnera7352392009-12-30 04:42:57 +00004081 // Null is a special case since it is typeless.
4082 if (EatIfPresent(lltok::kw_null)) {
4083 Elts.push_back(0);
4084 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00004085 }
Michael Ilseman407a6162012-11-15 22:34:00 +00004086
Chris Lattnera7352392009-12-30 04:42:57 +00004087 Value *V = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00004088 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00004089 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004090 } while (EatIfPresent(lltok::comma));
4091
4092 return false;
4093}