blob: 7b7e785547e5efcf36d5e253913e608604749d23 [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 Lattner0cd0d882011-06-18 21:18:23 +000029static std::string getTypeString(const Type *T) {
30 std::string Result;
31 raw_string_ostream Tmp(Result);
32 Tmp << *T;
33 return Tmp.str();
34}
35
Chris Lattner3ed88ef2009-01-02 08:05:26 +000036/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000037bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000038 // Prime the lexer.
39 Lex.Lex();
40
Chris Lattnerad7d1e22009-01-04 20:44:11 +000041 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000043}
44
45/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
46/// module.
47bool LLParser::ValidateEndOfModule() {
Chris Lattner449c3102010-04-01 05:14:45 +000048 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
52 I != E; ++I) {
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
55
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
58
59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +000061 Twine(SlotNo) + "'");
Chris Lattner449c3102010-04-01 05:14:45 +000062 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
63 }
64 }
65 ForwardRefInstMetadata.clear();
66 }
67
68
Chris Lattner09d9ef42009-10-28 03:39:23 +000069 // If there are entries in ForwardRefBlockAddresses at this point, they are
70 // references after the function was defined. Resolve those now.
71 while (!ForwardRefBlockAddresses.empty()) {
72 // Okay, we are referencing an already-parsed function, resolve them now.
73 Function *TheFn = 0;
74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
75 if (Fn.Kind == ValID::t_GlobalName)
76 TheFn = M->getFunction(Fn.StrVal);
77 else if (Fn.UIntVal < NumberedVals.size())
78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
79
80 if (TheFn == 0)
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
82
83 // Resolve all these references.
84 if (ResolveForwardRefBlockAddresses(TheFn,
85 ForwardRefBlockAddresses.begin()->second,
86 0))
87 return true;
88
89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
90 }
91
92
Chris Lattnerdf986172009-01-02 07:01:27 +000093 if (!ForwardRefTypes.empty())
94 return Error(ForwardRefTypes.begin()->second.second,
95 "use of undefined type named '" +
96 ForwardRefTypes.begin()->first + "'");
97 if (!ForwardRefTypeIDs.empty())
98 return Error(ForwardRefTypeIDs.begin()->second.second,
99 "use of undefined type '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000100 Twine(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000101
Chris Lattnerdf986172009-01-02 07:01:27 +0000102 if (!ForwardRefVals.empty())
103 return Error(ForwardRefVals.begin()->second.second,
104 "use of undefined value '@" + ForwardRefVals.begin()->first +
105 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000106
Chris Lattnerdf986172009-01-02 07:01:27 +0000107 if (!ForwardRefValIDs.empty())
108 return Error(ForwardRefValIDs.begin()->second.second,
109 "use of undefined value '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000110 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000111
Devang Patel1c7eea62009-07-08 19:23:54 +0000112 if (!ForwardRefMDNodes.empty())
113 return Error(ForwardRefMDNodes.begin()->second.second,
114 "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000115 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000116
Devang Patel1c7eea62009-07-08 19:23:54 +0000117
Chris Lattnerdf986172009-01-02 07:01:27 +0000118 // Look for intrinsic functions and CallInst that need to be upgraded
119 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
120 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000121
Devang Patele4b27562009-08-28 23:24:31 +0000122 // Check debug info intrinsics.
123 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000124 return false;
125}
126
Chris Lattner09d9ef42009-10-28 03:39:23 +0000127bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
128 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
129 PerFunctionState *PFS) {
130 // Loop over all the references, resolving them.
131 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
132 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000133 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000134 if (Refs[i].first.Kind == ValID::t_LocalName)
135 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000136 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000137 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
138 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
139 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000140 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000141 } else {
142 Res = dyn_cast_or_null<BasicBlock>(
143 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
144 }
145
Chris Lattnercdfc9402009-11-01 01:27:45 +0000146 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000147 return Error(Refs[i].first.Loc,
148 "referenced value is not a basic block");
149
150 // Get the BlockAddress for this and update references to use it.
151 BlockAddress *BA = BlockAddress::get(TheFn, Res);
152 Refs[i].second->replaceAllUsesWith(BA);
153 Refs[i].second->eraseFromParent();
154 }
155 return false;
156}
157
158
Chris Lattnerdf986172009-01-02 07:01:27 +0000159//===----------------------------------------------------------------------===//
160// Top-Level Entities
161//===----------------------------------------------------------------------===//
162
163bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000164 while (1) {
165 switch (Lex.getKind()) {
166 default: return TokError("expected top-level entity");
167 case lltok::Eof: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000168 case lltok::kw_declare: if (ParseDeclare()) return true; break;
169 case lltok::kw_define: if (ParseDefine()) return true; break;
170 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
171 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
172 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000173 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000174 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000175 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000176 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000177 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000178 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000179
180 // The Global variable production with no name can have many different
181 // optional leading prefixes, the production is:
182 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000183 // OptionalAddrSpace OptionalUnNammedAddr
184 // ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000185 case lltok::kw_private: // OptionalLinkage
186 case lltok::kw_linker_private: // OptionalLinkage
187 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling55ae5152010-08-20 22:05:50 +0000188 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000189 case lltok::kw_internal: // OptionalLinkage
190 case lltok::kw_weak: // OptionalLinkage
191 case lltok::kw_weak_odr: // OptionalLinkage
192 case lltok::kw_linkonce: // OptionalLinkage
193 case lltok::kw_linkonce_odr: // OptionalLinkage
194 case lltok::kw_appending: // OptionalLinkage
195 case lltok::kw_dllexport: // OptionalLinkage
196 case lltok::kw_common: // OptionalLinkage
197 case lltok::kw_dllimport: // OptionalLinkage
198 case lltok::kw_extern_weak: // OptionalLinkage
199 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000200 unsigned Linkage, Visibility;
201 if (ParseOptionalLinkage(Linkage) ||
202 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000203 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000204 return true;
205 break;
206 }
207 case lltok::kw_default: // OptionalVisibility
208 case lltok::kw_hidden: // OptionalVisibility
209 case lltok::kw_protected: { // OptionalVisibility
210 unsigned Visibility;
211 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000212 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000213 return true;
214 break;
215 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000216
Chris Lattnerdf986172009-01-02 07:01:27 +0000217 case lltok::kw_thread_local: // OptionalThreadLocal
218 case lltok::kw_addrspace: // OptionalAddrSpace
219 case lltok::kw_constant: // GlobalType
220 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000221 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000222 break;
223 }
224 }
225}
226
227
228/// toplevelentity
229/// ::= 'module' 'asm' STRINGCONSTANT
230bool LLParser::ParseModuleAsm() {
231 assert(Lex.getKind() == lltok::kw_module);
232 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000233
234 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000235 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
236 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000237
Rafael Espindola38c4e532011-03-02 04:14:42 +0000238 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000239 return false;
240}
241
242/// toplevelentity
243/// ::= 'target' 'triple' '=' STRINGCONSTANT
244/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
245bool LLParser::ParseTargetDefinition() {
246 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000247 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000248 switch (Lex.Lex()) {
249 default: return TokError("unknown target property");
250 case lltok::kw_triple:
251 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000252 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
253 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000254 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000255 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000256 return false;
257 case lltok::kw_datalayout:
258 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000259 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
260 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000261 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000262 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000263 return false;
264 }
265}
266
267/// toplevelentity
268/// ::= 'deplibs' '=' '[' ']'
269/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
270bool LLParser::ParseDepLibs() {
271 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000272 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000273 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
274 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
275 return true;
276
277 if (EatIfPresent(lltok::rsquare))
278 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000279
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000280 std::string Str;
281 if (ParseStringConstant(Str)) return true;
282 M->addLibrary(Str);
283
284 while (EatIfPresent(lltok::comma)) {
285 if (ParseStringConstant(Str)) return true;
286 M->addLibrary(Str);
287 }
288
289 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000290}
291
Dan Gohman3845e502009-08-12 23:32:33 +0000292/// ParseUnnamedType:
Dan Gohman3845e502009-08-12 23:32:33 +0000293/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000294bool LLParser::ParseUnnamedType() {
Chris Lattneredcaca82011-06-18 23:51:31 +0000295 LocTy TypeLoc = Lex.getLoc();
Chris Lattnera53616d2011-06-19 00:03:46 +0000296 unsigned TypeID = NumberedTypes.size();
297 if (Lex.getUIntVal() != TypeID)
298 return Error(Lex.getLoc(), "type expected to be numbered '%" +
299 Twine(TypeID) + "'");
300 Lex.Lex(); // eat LocalVarID;
301
302 if (ParseToken(lltok::equal, "expected '=' after name") ||
303 ParseToken(lltok::kw_type, "expected 'type' after '='"))
304 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000305
Owen Anderson1d0be152009-08-13 21:58:54 +0000306 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000307 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000308
Chris Lattnerdf986172009-01-02 07:01:27 +0000309 // See if this type was previously referenced.
310 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
311 FI = ForwardRefTypeIDs.find(TypeID);
312 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000313 if (FI->second.first.get() == Ty)
314 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000315
Chris Lattnerdf986172009-01-02 07:01:27 +0000316 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
317 Ty = FI->second.first.get();
318 ForwardRefTypeIDs.erase(FI);
319 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000320
Chris Lattnerdf986172009-01-02 07:01:27 +0000321 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000322
Chris Lattnerdf986172009-01-02 07:01:27 +0000323 return false;
324}
325
326/// toplevelentity
327/// ::= LocalVar '=' 'type' type
328bool LLParser::ParseNamedType() {
329 std::string Name = Lex.getStrVal();
330 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000331 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000332
Owen Anderson1d0be152009-08-13 21:58:54 +0000333 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000334
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000335 if (ParseToken(lltok::equal, "expected '=' after name") ||
336 ParseToken(lltok::kw_type, "expected 'type' after name") ||
337 ParseType(Ty))
338 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000339
Chris Lattnerdf986172009-01-02 07:01:27 +0000340 // Set the type name, checking for conflicts as we do so.
341 bool AlreadyExists = M->addTypeName(Name, Ty);
342 if (!AlreadyExists) return false;
343
344 // See if this type is a forward reference. We need to eagerly resolve
345 // types to allow recursive type redefinitions below.
346 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
347 FI = ForwardRefTypes.find(Name);
348 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000349 if (FI->second.first.get() == Ty)
350 return Error(NameLoc, "self referential type is invalid");
351
Chris Lattnerdf986172009-01-02 07:01:27 +0000352 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
353 Ty = FI->second.first.get();
354 ForwardRefTypes.erase(FI);
Chris Lattnerd5890992011-06-17 07:06:44 +0000355 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000356 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000357
Chris Lattnerdf986172009-01-02 07:01:27 +0000358 // Inserting a name that is already defined, get the existing name.
Matt Beaumont-Gayd3e724a2011-06-17 22:21:12 +0000359 assert(M->getTypeByName(Name) && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000360
Chris Lattnerd5890992011-06-17 07:06:44 +0000361 // Otherwise, this is an attempt to redefine a type, report the error.
Chris Lattnerdf986172009-01-02 07:01:27 +0000362 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000363 getTypeString(Ty) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000364}
365
366
367/// toplevelentity
368/// ::= 'declare' FunctionHeader
369bool LLParser::ParseDeclare() {
370 assert(Lex.getKind() == lltok::kw_declare);
371 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000372
Chris Lattnerdf986172009-01-02 07:01:27 +0000373 Function *F;
374 return ParseFunctionHeader(F, false);
375}
376
377/// toplevelentity
378/// ::= 'define' FunctionHeader '{' ...
379bool LLParser::ParseDefine() {
380 assert(Lex.getKind() == lltok::kw_define);
381 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000382
Chris Lattnerdf986172009-01-02 07:01:27 +0000383 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000384 return ParseFunctionHeader(F, true) ||
385 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000386}
387
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000388/// ParseGlobalType
389/// ::= 'constant'
390/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000391bool LLParser::ParseGlobalType(bool &IsConstant) {
392 if (Lex.getKind() == lltok::kw_constant)
393 IsConstant = true;
394 else if (Lex.getKind() == lltok::kw_global)
395 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000396 else {
397 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000398 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000399 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000400 Lex.Lex();
401 return false;
402}
403
Dan Gohman3845e502009-08-12 23:32:33 +0000404/// ParseUnnamedGlobal:
405/// OptionalVisibility ALIAS ...
406/// OptionalLinkage OptionalVisibility ... -> global variable
407/// GlobalID '=' OptionalVisibility ALIAS ...
408/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
409bool LLParser::ParseUnnamedGlobal() {
410 unsigned VarID = NumberedVals.size();
411 std::string Name;
412 LocTy NameLoc = Lex.getLoc();
413
414 // Handle the GlobalID form.
415 if (Lex.getKind() == lltok::GlobalID) {
416 if (Lex.getUIntVal() != VarID)
417 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000418 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000419 Lex.Lex(); // eat GlobalID;
420
421 if (ParseToken(lltok::equal, "expected '=' after name"))
422 return true;
423 }
424
425 bool HasLinkage;
426 unsigned Linkage, Visibility;
427 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
428 ParseOptionalVisibility(Visibility))
429 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000430
Dan Gohman3845e502009-08-12 23:32:33 +0000431 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
432 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
433 return ParseAlias(Name, NameLoc, Visibility);
434}
435
Chris Lattnerdf986172009-01-02 07:01:27 +0000436/// ParseNamedGlobal:
437/// GlobalVar '=' OptionalVisibility ALIAS ...
438/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
439bool LLParser::ParseNamedGlobal() {
440 assert(Lex.getKind() == lltok::GlobalVar);
441 LocTy NameLoc = Lex.getLoc();
442 std::string Name = Lex.getStrVal();
443 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000444
Chris Lattnerdf986172009-01-02 07:01:27 +0000445 bool HasLinkage;
446 unsigned Linkage, Visibility;
447 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
448 ParseOptionalLinkage(Linkage, HasLinkage) ||
449 ParseOptionalVisibility(Visibility))
450 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000451
Chris Lattnerdf986172009-01-02 07:01:27 +0000452 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
453 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
454 return ParseAlias(Name, NameLoc, Visibility);
455}
456
Devang Patel256be962009-07-20 19:00:08 +0000457// MDString:
458// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000459bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000460 std::string Str;
461 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000462 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000463 return false;
464}
465
466// MDNode:
467// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000468//
469/// This version of ParseMDNodeID returns the slot number and null in the case
470/// of a forward reference.
471bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
472 // !{ ..., !42, ... }
473 if (ParseUInt32(SlotNo)) return true;
474
475 // Check existing MDNode.
476 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
477 Result = NumberedMetadata[SlotNo];
478 else
479 Result = 0;
480 return false;
481}
482
Chris Lattner4a72efc2009-12-30 04:15:23 +0000483bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000484 // !{ ..., !42, ... }
485 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000486 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000487
Chris Lattner449c3102010-04-01 05:14:45 +0000488 // If not a forward reference, just return it now.
489 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000490
Chris Lattner449c3102010-04-01 05:14:45 +0000491 // Otherwise, create MDNode forward reference.
Jay Foadec9186b2011-04-21 19:59:31 +0000492 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Patel256be962009-07-20 19:00:08 +0000493 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000494
495 if (NumberedMetadata.size() <= MID)
496 NumberedMetadata.resize(MID+1);
497 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000498 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000499 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000500}
Devang Patel256be962009-07-20 19:00:08 +0000501
Chris Lattner84d03b12009-12-29 22:35:39 +0000502/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000503/// !foo = !{ !1, !2 }
504bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000505 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000506 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000507 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000508
Chris Lattner84d03b12009-12-29 22:35:39 +0000509 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000510 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000511 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000512 return true;
513
Dan Gohman17aa92c2010-07-21 23:38:33 +0000514 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000515 if (Lex.getKind() != lltok::rbrace)
516 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000517 if (ParseToken(lltok::exclaim, "Expected '!' here"))
518 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000519
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000520 MDNode *N = 0;
521 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000522 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000523 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000524
525 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
526 return true;
527
Devang Pateleff2ab62009-07-29 00:34:02 +0000528 return false;
529}
530
Devang Patel923078c2009-07-01 19:21:12 +0000531/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000532/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000533bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000534 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000535 Lex.Lex();
536 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000537
538 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000539 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000540 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000541 if (ParseUInt32(MetadataID) ||
542 ParseToken(lltok::equal, "expected '=' here") ||
543 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000544 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000545 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000546 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000547 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000548 return true;
549
Jay Foadec9186b2011-04-21 19:59:31 +0000550 MDNode *Init = MDNode::get(Context, Elts);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000551
552 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000553 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000554 FI = ForwardRefMDNodes.find(MetadataID);
555 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000556 MDNode *Temp = FI->second.first;
557 Temp->replaceAllUsesWith(Init);
558 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000559 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000560
561 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
562 } else {
563 if (MetadataID >= NumberedMetadata.size())
564 NumberedMetadata.resize(MetadataID+1);
565
566 if (NumberedMetadata[MetadataID] != 0)
567 return TokError("Metadata id is already used");
568 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000569 }
570
Devang Patel923078c2009-07-01 19:21:12 +0000571 return false;
572}
573
Chris Lattnerdf986172009-01-02 07:01:27 +0000574/// ParseAlias:
575/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
576/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000577/// ::= TypeAndValue
578/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000579/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000580///
581/// Everything through visibility has already been parsed.
582///
583bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
584 unsigned Visibility) {
585 assert(Lex.getKind() == lltok::kw_alias);
586 Lex.Lex();
587 unsigned Linkage;
588 LocTy LinkageLoc = Lex.getLoc();
589 if (ParseOptionalLinkage(Linkage))
590 return true;
591
592 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000593 Linkage != GlobalValue::WeakAnyLinkage &&
594 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000595 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000596 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000597 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling55ae5152010-08-20 22:05:50 +0000598 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
599 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000600 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000601
Chris Lattnerdf986172009-01-02 07:01:27 +0000602 Constant *Aliasee;
603 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000604 if (Lex.getKind() != lltok::kw_bitcast &&
605 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000606 if (ParseGlobalTypeAndValue(Aliasee)) return true;
607 } else {
608 // The bitcast dest type is not present, it is implied by the dest type.
609 ValID ID;
610 if (ParseValID(ID)) return true;
611 if (ID.Kind != ValID::t_Constant)
612 return Error(AliaseeLoc, "invalid aliasee");
613 Aliasee = ID.ConstantVal;
614 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000615
Duncan Sands1df98592010-02-16 11:11:14 +0000616 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000617 return Error(AliaseeLoc, "alias must have pointer type");
618
619 // Okay, create the alias but do not insert it into the module yet.
620 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
621 (GlobalValue::LinkageTypes)Linkage, Name,
622 Aliasee);
623 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000624
Chris Lattnerdf986172009-01-02 07:01:27 +0000625 // See if this value already exists in the symbol table. If so, it is either
626 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000627 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000628 // See if this was a redefinition. If so, there is no entry in
629 // ForwardRefVals.
630 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
631 I = ForwardRefVals.find(Name);
632 if (I == ForwardRefVals.end())
633 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
634
635 // Otherwise, this was a definition of forward ref. Verify that types
636 // agree.
637 if (Val->getType() != GA->getType())
638 return Error(NameLoc,
639 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000640
Chris Lattnerdf986172009-01-02 07:01:27 +0000641 // If they agree, just RAUW the old value with the alias and remove the
642 // forward ref info.
643 Val->replaceAllUsesWith(GA);
644 Val->eraseFromParent();
645 ForwardRefVals.erase(I);
646 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000647
Chris Lattnerdf986172009-01-02 07:01:27 +0000648 // Insert into the module, we know its name won't collide now.
649 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000650 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000651
Chris Lattnerdf986172009-01-02 07:01:27 +0000652 return false;
653}
654
655/// ParseGlobal
656/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000657/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000658/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000659/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000660///
661/// Everything through visibility has been parsed already.
662///
663bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
664 unsigned Linkage, bool HasLinkage,
665 unsigned Visibility) {
666 unsigned AddrSpace;
Rafael Espindolabea46262011-01-08 16:42:36 +0000667 bool ThreadLocal, IsConstant, UnnamedAddr;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000668 LocTy UnnamedAddrLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000669 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000670
Owen Anderson1d0be152009-08-13 21:58:54 +0000671 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000672 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
673 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000674 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
675 &UnnamedAddrLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000676 ParseGlobalType(IsConstant) ||
677 ParseType(Ty, TyLoc))
678 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000679
Chris Lattnerdf986172009-01-02 07:01:27 +0000680 // If the linkage is specified and is external, then no initializer is
681 // present.
682 Constant *Init = 0;
683 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000684 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000685 Linkage != GlobalValue::ExternalLinkage)) {
686 if (ParseGlobalValue(Ty, Init))
687 return true;
688 }
689
Duncan Sands1df98592010-02-16 11:11:14 +0000690 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000691 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000692
Chris Lattnerdf986172009-01-02 07:01:27 +0000693 GlobalVariable *GV = 0;
694
695 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000696 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000697 if (GlobalValue *GVal = M->getNamedValue(Name)) {
698 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
699 return Error(NameLoc, "redefinition of global '@" + Name + "'");
700 GV = cast<GlobalVariable>(GVal);
701 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000702 } else {
703 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
704 I = ForwardRefValIDs.find(NumberedVals.size());
705 if (I != ForwardRefValIDs.end()) {
706 GV = cast<GlobalVariable>(I->second.first);
707 ForwardRefValIDs.erase(I);
708 }
709 }
710
711 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000712 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000713 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000714 } else {
715 if (GV->getType()->getElementType() != Ty)
716 return Error(TyLoc,
717 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000718
Chris Lattnerdf986172009-01-02 07:01:27 +0000719 // Move the forward-reference to the correct spot in the module.
720 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
721 }
722
723 if (Name.empty())
724 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000725
Chris Lattnerdf986172009-01-02 07:01:27 +0000726 // Set the parsed properties on the global.
727 if (Init)
728 GV->setInitializer(Init);
729 GV->setConstant(IsConstant);
730 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
731 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
732 GV->setThreadLocal(ThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +0000733 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000734
Chris Lattnerdf986172009-01-02 07:01:27 +0000735 // Parse attributes on the global.
736 while (Lex.getKind() == lltok::comma) {
737 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000738
Chris Lattnerdf986172009-01-02 07:01:27 +0000739 if (Lex.getKind() == lltok::kw_section) {
740 Lex.Lex();
741 GV->setSection(Lex.getStrVal());
742 if (ParseToken(lltok::StringConstant, "expected global section string"))
743 return true;
744 } else if (Lex.getKind() == lltok::kw_align) {
745 unsigned Alignment;
746 if (ParseOptionalAlignment(Alignment)) return true;
747 GV->setAlignment(Alignment);
748 } else {
749 TokError("unknown global variable property!");
750 }
751 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000752
Chris Lattnerdf986172009-01-02 07:01:27 +0000753 return false;
754}
755
756
757//===----------------------------------------------------------------------===//
758// GlobalValue Reference/Resolution Routines.
759//===----------------------------------------------------------------------===//
760
761/// GetGlobalVal - Get a value with the specified name or ID, creating a
762/// forward reference record if needed. This can return null if the value
763/// exists but does not have the right type.
764GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
765 LocTy Loc) {
766 const PointerType *PTy = dyn_cast<PointerType>(Ty);
767 if (PTy == 0) {
768 Error(Loc, "global variable reference must have pointer type");
769 return 0;
770 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000771
Chris Lattnerdf986172009-01-02 07:01:27 +0000772 // Look this name up in the normal function symbol table.
773 GlobalValue *Val =
774 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000775
Chris Lattnerdf986172009-01-02 07:01:27 +0000776 // If this is a forward reference for the value, see if we already created a
777 // forward ref record.
778 if (Val == 0) {
779 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
780 I = ForwardRefVals.find(Name);
781 if (I != ForwardRefVals.end())
782 Val = I->second.first;
783 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000784
Chris Lattnerdf986172009-01-02 07:01:27 +0000785 // If we have the value in the symbol table or fwd-ref table, return it.
786 if (Val) {
787 if (Val->getType() == Ty) return Val;
788 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000789 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000790 return 0;
791 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000792
Chris Lattnerdf986172009-01-02 07:01:27 +0000793 // Otherwise, create a new forward reference for this value and remember it.
794 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000795 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
796 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000797 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000798 Error(Loc, "function may not return opaque type");
799 return 0;
800 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000801
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000802 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000803 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000804 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
805 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000806 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000807
Chris Lattnerdf986172009-01-02 07:01:27 +0000808 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
809 return FwdVal;
810}
811
812GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
813 const PointerType *PTy = dyn_cast<PointerType>(Ty);
814 if (PTy == 0) {
815 Error(Loc, "global variable reference must have pointer type");
816 return 0;
817 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000818
Chris Lattnerdf986172009-01-02 07:01:27 +0000819 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000820
Chris Lattnerdf986172009-01-02 07:01:27 +0000821 // If this is a forward reference for the value, see if we already created a
822 // forward ref record.
823 if (Val == 0) {
824 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
825 I = ForwardRefValIDs.find(ID);
826 if (I != ForwardRefValIDs.end())
827 Val = I->second.first;
828 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000829
Chris Lattnerdf986172009-01-02 07:01:27 +0000830 // If we have the value in the symbol table or fwd-ref table, return it.
831 if (Val) {
832 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000833 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000834 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000835 return 0;
836 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000837
Chris Lattnerdf986172009-01-02 07:01:27 +0000838 // Otherwise, create a new forward reference for this value and remember it.
839 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000840 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
841 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000842 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000843 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000844 return 0;
845 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000846 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000847 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000848 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
849 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000850 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000851
Chris Lattnerdf986172009-01-02 07:01:27 +0000852 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
853 return FwdVal;
854}
855
856
857//===----------------------------------------------------------------------===//
858// Helper Routines.
859//===----------------------------------------------------------------------===//
860
861/// ParseToken - If the current token has the specified kind, eat it and return
862/// success. Otherwise, emit the specified error and return failure.
863bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
864 if (Lex.getKind() != T)
865 return TokError(ErrMsg);
866 Lex.Lex();
867 return false;
868}
869
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000870/// ParseStringConstant
871/// ::= StringConstant
872bool LLParser::ParseStringConstant(std::string &Result) {
873 if (Lex.getKind() != lltok::StringConstant)
874 return TokError("expected string constant");
875 Result = Lex.getStrVal();
876 Lex.Lex();
877 return false;
878}
879
880/// ParseUInt32
881/// ::= uint32
882bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000883 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
884 return TokError("expected integer");
885 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
886 if (Val64 != unsigned(Val64))
887 return TokError("expected 32-bit integer (too large)");
888 Val = Val64;
889 Lex.Lex();
890 return false;
891}
892
893
894/// ParseOptionalAddrSpace
895/// := /*empty*/
896/// := 'addrspace' '(' uint32 ')'
897bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
898 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000899 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000900 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000901 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000902 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000903 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000904}
Chris Lattnerdf986172009-01-02 07:01:27 +0000905
906/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
907/// indicates what kind of attribute list this is: 0: function arg, 1: result,
908/// 2: function attr.
909bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
910 Attrs = Attribute::None;
911 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000912
Chris Lattnerdf986172009-01-02 07:01:27 +0000913 while (1) {
914 switch (Lex.getKind()) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000915 default: // End of attributes.
916 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
917 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000918
Chris Lattnerf3a789d2011-06-17 03:16:47 +0000919 // As a hack, we allow "align 2" on functions as a synonym for
920 // "alignstack 2".
921 if (AttrKind == 2 &&
922 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
923 return Error(AttrLoc, "invalid use of attribute on a function");
924
925 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000926 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000927
Chris Lattnerdf986172009-01-02 07:01:27 +0000928 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000929 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
930 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
931 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
932 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
933 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
934 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
935 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
936 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000937
Devang Patel578efa92009-06-05 21:57:13 +0000938 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
939 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000940 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
Devang Patel578efa92009-06-05 21:57:13 +0000941 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
942 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
943 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000944 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000945 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
946 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
947 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
948 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
949 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
950 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000951 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Charles Davis970bfcc2010-10-25 15:37:09 +0000952 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
John McCall3a3465b2011-06-15 20:36:13 +0000953 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000954
Charles Davis1e063d12010-02-12 00:31:15 +0000955 case lltok::kw_alignstack: {
956 unsigned Alignment;
957 if (ParseOptionalStackAlignment(Alignment))
958 return true;
959 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
960 continue;
961 }
962
Chris Lattnerdf986172009-01-02 07:01:27 +0000963 case lltok::kw_align: {
964 unsigned Alignment;
965 if (ParseOptionalAlignment(Alignment))
966 return true;
967 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
968 continue;
969 }
Charles Davis1e063d12010-02-12 00:31:15 +0000970
Chris Lattnerdf986172009-01-02 07:01:27 +0000971 }
972 Lex.Lex();
973 }
974}
975
976/// ParseOptionalLinkage
977/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000978/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000979/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +0000980/// ::= 'linker_private_weak'
Bill Wendling55ae5152010-08-20 22:05:50 +0000981/// ::= 'linker_private_weak_def_auto'
Chris Lattnerdf986172009-01-02 07:01:27 +0000982/// ::= 'internal'
983/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000984/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000985/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000986/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +0000987/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +0000988/// ::= 'appending'
989/// ::= 'dllexport'
990/// ::= 'common'
991/// ::= 'dllimport'
992/// ::= 'extern_weak'
993/// ::= 'external'
994bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
995 HasLinkage = false;
996 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000997 default: Res=GlobalValue::ExternalLinkage; return false;
998 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
999 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001000 case lltok::kw_linker_private_weak:
1001 Res = GlobalValue::LinkerPrivateWeakLinkage;
1002 break;
Bill Wendling55ae5152010-08-20 22:05:50 +00001003 case lltok::kw_linker_private_weak_def_auto:
1004 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1005 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001006 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1007 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1008 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1009 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1010 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001011 case lltok::kw_available_externally:
1012 Res = GlobalValue::AvailableExternallyLinkage;
1013 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001014 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1015 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1016 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1017 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1018 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1019 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001020 }
1021 Lex.Lex();
1022 HasLinkage = true;
1023 return false;
1024}
1025
1026/// ParseOptionalVisibility
1027/// ::= /*empty*/
1028/// ::= 'default'
1029/// ::= 'hidden'
1030/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001031///
Chris Lattnerdf986172009-01-02 07:01:27 +00001032bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1033 switch (Lex.getKind()) {
1034 default: Res = GlobalValue::DefaultVisibility; return false;
1035 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1036 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1037 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1038 }
1039 Lex.Lex();
1040 return false;
1041}
1042
1043/// ParseOptionalCallingConv
1044/// ::= /*empty*/
1045/// ::= 'ccc'
1046/// ::= 'fastcc'
1047/// ::= 'coldcc'
1048/// ::= 'x86_stdcallcc'
1049/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001050/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001051/// ::= 'arm_apcscc'
1052/// ::= 'arm_aapcscc'
1053/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001054/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001055/// ::= 'ptx_kernel'
1056/// ::= 'ptx_device'
Chris Lattnerdf986172009-01-02 07:01:27 +00001057/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001058///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001059bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001060 switch (Lex.getKind()) {
1061 default: CC = CallingConv::C; return false;
1062 case lltok::kw_ccc: CC = CallingConv::C; break;
1063 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1064 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1065 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1066 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001067 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001068 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1069 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1070 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001071 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001072 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1073 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001074 case lltok::kw_cc: {
1075 unsigned ArbitraryCC;
1076 Lex.Lex();
1077 if (ParseUInt32(ArbitraryCC)) {
1078 return true;
1079 } else
1080 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1081 return false;
1082 }
1083 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001084 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001085
Chris Lattnerdf986172009-01-02 07:01:27 +00001086 Lex.Lex();
1087 return false;
1088}
1089
Chris Lattnerb8c46862009-12-30 05:31:19 +00001090/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001091/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001092bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1093 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001094 do {
1095 if (Lex.getKind() != lltok::MetadataVar)
1096 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001097
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001098 std::string Name = Lex.getStrVal();
Dan Gohman309b3af2010-08-24 02:24:03 +00001099 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001100 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001101
Chris Lattner442ffa12009-12-29 21:53:55 +00001102 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001103 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001104
1105 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001106 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001107
Dan Gohman68261142010-08-24 14:35:45 +00001108 // This code is similar to that of ParseMetadataValue, however it needs to
1109 // have special-case code for a forward reference; see the comments on
1110 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1111 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001112 if (Lex.getKind() == lltok::lbrace) {
1113 ValID ID;
1114 if (ParseMetadataListValue(ID, PFS))
1115 return true;
1116 assert(ID.Kind == ValID::t_MDNode);
1117 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001118 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001119 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001120 if (ParseMDNodeID(Node, NodeID))
1121 return true;
1122 if (Node) {
1123 // If we got the node, add it to the instruction.
1124 Inst->setMetadata(MDK, Node);
1125 } else {
1126 MDRef R = { Loc, MDK, NodeID };
1127 // Otherwise, remember that this should be resolved later.
1128 ForwardRefInstMetadata[Inst].push_back(R);
1129 }
Chris Lattner449c3102010-04-01 05:14:45 +00001130 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001131
1132 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001133 } while (EatIfPresent(lltok::comma));
1134 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001135}
1136
Chris Lattnerdf986172009-01-02 07:01:27 +00001137/// ParseOptionalAlignment
1138/// ::= /* empty */
1139/// ::= 'align' 4
1140bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1141 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001142 if (!EatIfPresent(lltok::kw_align))
1143 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001144 LocTy AlignLoc = Lex.getLoc();
1145 if (ParseUInt32(Alignment)) return true;
1146 if (!isPowerOf2_32(Alignment))
1147 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001148 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001149 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001150 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001151}
1152
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001153/// ParseOptionalCommaAlign
1154/// ::=
1155/// ::= ',' align 4
1156///
1157/// This returns with AteExtraComma set to true if it ate an excess comma at the
1158/// end.
1159bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1160 bool &AteExtraComma) {
1161 AteExtraComma = false;
1162 while (EatIfPresent(lltok::comma)) {
1163 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001164 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001165 AteExtraComma = true;
1166 return false;
1167 }
1168
Chris Lattner093eed12010-04-23 00:50:50 +00001169 if (Lex.getKind() != lltok::kw_align)
1170 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001171
Chris Lattner093eed12010-04-23 00:50:50 +00001172 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001173 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001174
Devang Patelf633a062009-09-17 23:04:48 +00001175 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001176}
1177
Charles Davis1e063d12010-02-12 00:31:15 +00001178/// ParseOptionalStackAlignment
1179/// ::= /* empty */
1180/// ::= 'alignstack' '(' 4 ')'
1181bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1182 Alignment = 0;
1183 if (!EatIfPresent(lltok::kw_alignstack))
1184 return false;
1185 LocTy ParenLoc = Lex.getLoc();
1186 if (!EatIfPresent(lltok::lparen))
1187 return Error(ParenLoc, "expected '('");
1188 LocTy AlignLoc = Lex.getLoc();
1189 if (ParseUInt32(Alignment)) return true;
1190 ParenLoc = Lex.getLoc();
1191 if (!EatIfPresent(lltok::rparen))
1192 return Error(ParenLoc, "expected ')'");
1193 if (!isPowerOf2_32(Alignment))
1194 return Error(AlignLoc, "stack alignment is not a power of two");
1195 return false;
1196}
Devang Patelf633a062009-09-17 23:04:48 +00001197
Chris Lattner628c13a2009-12-30 05:14:00 +00001198/// ParseIndexList - This parses the index list for an insert/extractvalue
1199/// instruction. This sets AteExtraComma in the case where we eat an extra
1200/// comma at the end of the line and find that it is followed by metadata.
1201/// Clients that don't allow metadata can call the version of this function that
1202/// only takes one argument.
1203///
Chris Lattnerdf986172009-01-02 07:01:27 +00001204/// ParseIndexList
1205/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001206///
1207bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1208 bool &AteExtraComma) {
1209 AteExtraComma = false;
1210
Chris Lattnerdf986172009-01-02 07:01:27 +00001211 if (Lex.getKind() != lltok::comma)
1212 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001213
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001214 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001215 if (Lex.getKind() == lltok::MetadataVar) {
1216 AteExtraComma = true;
1217 return false;
1218 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001219 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001220 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001221 Indices.push_back(Idx);
1222 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001223
Chris Lattnerdf986172009-01-02 07:01:27 +00001224 return false;
1225}
1226
1227//===----------------------------------------------------------------------===//
1228// Type Parsing.
1229//===----------------------------------------------------------------------===//
1230
1231/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001232bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1233 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001234 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001235
Chris Lattnerdf986172009-01-02 07:01:27 +00001236 // Verify no unresolved uprefs.
1237 if (!UpRefs.empty())
1238 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001239
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001240 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001241 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001242
Chris Lattnerdf986172009-01-02 07:01:27 +00001243 return false;
1244}
1245
1246/// HandleUpRefs - Every time we finish a new layer of types, this function is
1247/// called. It loops through the UpRefs vector, which is a list of the
1248/// currently active types. For each type, if the up-reference is contained in
1249/// the newly completed type, we decrement the level count. When the level
1250/// count reaches zero, the up-referenced type is the type that is passed in:
1251/// thus we can complete the cycle.
1252///
1253PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1254 // If Ty isn't abstract, or if there are no up-references in it, then there is
1255 // nothing to resolve here.
1256 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001257
Chris Lattnerdf986172009-01-02 07:01:27 +00001258 PATypeHolder Ty(ty);
1259#if 0
Chris Lattner0cd0d882011-06-18 21:18:23 +00001260 dbgs() << "Type '" << *Ty
Chris Lattnerdf986172009-01-02 07:01:27 +00001261 << "' newly formed. Resolving upreferences.\n"
1262 << UpRefs.size() << " upreferences active!\n";
1263#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001264
Chris Lattnerdf986172009-01-02 07:01:27 +00001265 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1266 // to zero), we resolve them all together before we resolve them to Ty. At
1267 // the end of the loop, if there is anything to resolve to Ty, it will be in
1268 // this variable.
1269 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001270
Chris Lattnerdf986172009-01-02 07:01:27 +00001271 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1272 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1273 bool ContainsType =
1274 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1275 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001276
Chris Lattnerdf986172009-01-02 07:01:27 +00001277#if 0
Chris Lattner0cd0d882011-06-18 21:18:23 +00001278 dbgs() << " UR#" << i << " - TypeContains(" << *Ty << ", "
1279 << *UpRefs[i].LastContainedTy << ") = "
Chris Lattnerdf986172009-01-02 07:01:27 +00001280 << (ContainsType ? "true" : "false")
1281 << " level=" << UpRefs[i].NestingLevel << "\n";
1282#endif
1283 if (!ContainsType)
1284 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001285
Chris Lattnerdf986172009-01-02 07:01:27 +00001286 // Decrement level of upreference
1287 unsigned Level = --UpRefs[i].NestingLevel;
1288 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001289
Chris Lattnerdf986172009-01-02 07:01:27 +00001290 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1291 if (Level != 0)
1292 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001293
Chris Lattnerdf986172009-01-02 07:01:27 +00001294#if 0
David Greene0e28d762009-12-23 23:38:28 +00001295 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001296#endif
1297 if (!TypeToResolve)
1298 TypeToResolve = UpRefs[i].UpRefTy;
1299 else
1300 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1301 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1302 --i; // Do not skip the next element.
1303 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001304
Chris Lattnerdf986172009-01-02 07:01:27 +00001305 if (TypeToResolve)
1306 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001307
Chris Lattnerdf986172009-01-02 07:01:27 +00001308 return Ty;
1309}
1310
1311
1312/// ParseTypeRec - The recursive function used to process the internal
1313/// implementation details of types.
1314bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1315 switch (Lex.getKind()) {
1316 default:
1317 return TokError("expected type");
1318 case lltok::Type:
1319 // TypeRec ::= 'float' | 'void' (etc)
1320 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001321 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001322 break;
1323 case lltok::kw_opaque:
1324 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001325 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001326 Lex.Lex();
1327 break;
1328 case lltok::lbrace:
1329 // TypeRec ::= '{' ... '}'
1330 if (ParseStructType(Result, false))
1331 return true;
1332 break;
1333 case lltok::lsquare:
1334 // TypeRec ::= '[' ... ']'
1335 Lex.Lex(); // eat the lsquare.
1336 if (ParseArrayVectorType(Result, false))
1337 return true;
1338 break;
1339 case lltok::less: // Either vector or packed struct.
1340 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001341 Lex.Lex();
1342 if (Lex.getKind() == lltok::lbrace) {
1343 if (ParseStructType(Result, true) ||
1344 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001345 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001346 } else if (ParseArrayVectorType(Result, true))
1347 return true;
1348 break;
1349 case lltok::LocalVar:
Chris Lattnerdf986172009-01-02 07:01:27 +00001350 // TypeRec ::= %foo
1351 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1352 Result = T;
1353 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001354 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001355 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1356 std::make_pair(Result,
1357 Lex.getLoc())));
1358 M->addTypeName(Lex.getStrVal(), Result.get());
1359 }
1360 Lex.Lex();
1361 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001362
Chris Lattnerdf986172009-01-02 07:01:27 +00001363 case lltok::LocalVarID:
1364 // TypeRec ::= %4
1365 if (Lex.getUIntVal() < NumberedTypes.size())
1366 Result = NumberedTypes[Lex.getUIntVal()];
1367 else {
1368 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1369 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1370 if (I != ForwardRefTypeIDs.end())
1371 Result = I->second.first;
1372 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001373 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001374 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1375 std::make_pair(Result,
1376 Lex.getLoc())));
1377 }
1378 }
1379 Lex.Lex();
1380 break;
1381 case lltok::backslash: {
1382 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001383 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001384 unsigned Val;
1385 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001386 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001387 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1388 Result = OT;
1389 break;
1390 }
1391 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001392
1393 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001394 while (1) {
1395 switch (Lex.getKind()) {
1396 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001397 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001398
1399 // TypeRec ::= TypeRec '*'
1400 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001401 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001402 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001403 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001404 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001405 if (!PointerType::isValidElementType(Result.get()))
1406 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001407 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001408 Lex.Lex();
1409 break;
1410
1411 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1412 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001413 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001414 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001415 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001416 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001417 if (!PointerType::isValidElementType(Result.get()))
1418 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001419 unsigned AddrSpace;
1420 if (ParseOptionalAddrSpace(AddrSpace) ||
1421 ParseToken(lltok::star, "expected '*' in address space"))
1422 return true;
1423
Owen Andersondebcb012009-07-29 22:17:13 +00001424 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001425 break;
1426 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001427
Chris Lattnerdf986172009-01-02 07:01:27 +00001428 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1429 case lltok::lparen:
1430 if (ParseFunctionType(Result))
1431 return true;
1432 break;
1433 }
1434 }
1435}
1436
1437/// ParseParameterList
1438/// ::= '(' ')'
1439/// ::= '(' Arg (',' Arg)* ')'
1440/// Arg
1441/// ::= Type OptionalAttributes Value OptionalAttributes
1442bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1443 PerFunctionState &PFS) {
1444 if (ParseToken(lltok::lparen, "expected '(' in call"))
1445 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001446
Chris Lattnerdf986172009-01-02 07:01:27 +00001447 while (Lex.getKind() != lltok::rparen) {
1448 // If this isn't the first argument, we need a comma.
1449 if (!ArgList.empty() &&
1450 ParseToken(lltok::comma, "expected ',' in argument list"))
1451 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001452
Chris Lattnerdf986172009-01-02 07:01:27 +00001453 // Parse the argument.
1454 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001455 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001456 unsigned ArgAttrs1 = Attribute::None;
1457 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001458 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001459 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001460 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001461
Chris Lattner287881d2009-12-30 02:11:14 +00001462 // Otherwise, handle normal operands.
Chris Lattnerf3a789d2011-06-17 03:16:47 +00001463 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001464 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001465 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1466 }
1467
1468 Lex.Lex(); // Lex the ')'.
1469 return false;
1470}
1471
1472
1473
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001474/// ParseArgumentList - Parse the argument list for a function type or function
1475/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001476/// ::= '(' ArgTypeListI ')'
1477/// ArgTypeListI
1478/// ::= /*empty*/
1479/// ::= '...'
1480/// ::= ArgTypeList ',' '...'
1481/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001482///
Chris Lattnerdf986172009-01-02 07:01:27 +00001483bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001484 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001485 isVarArg = false;
1486 assert(Lex.getKind() == lltok::lparen);
1487 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001488
Chris Lattnerdf986172009-01-02 07:01:27 +00001489 if (Lex.getKind() == lltok::rparen) {
1490 // empty
1491 } else if (Lex.getKind() == lltok::dotdotdot) {
1492 isVarArg = true;
1493 Lex.Lex();
1494 } else {
1495 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001496 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001497 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001498 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001499
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001500 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1501 // types (such as a function returning a pointer to itself). If parsing a
1502 // function prototype, we require fully resolved types.
1503 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001504 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001505
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001506 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001507 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001508
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001509 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001510 Name = Lex.getStrVal();
1511 Lex.Lex();
1512 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001513
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001514 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001515 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001516
Chris Lattnerdf986172009-01-02 07:01:27 +00001517 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001518
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001519 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001520 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001521 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001522 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001523 break;
1524 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001525
Chris Lattnerdf986172009-01-02 07:01:27 +00001526 // Otherwise must be an argument type.
1527 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001528 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001529 ParseOptionalAttrs(Attrs, 0)) return true;
1530
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001531 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001532 return Error(TypeLoc, "argument can not have void type");
1533
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001534 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001535 Name = Lex.getStrVal();
1536 Lex.Lex();
1537 } else {
1538 Name = "";
1539 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001540
Duncan Sands47c51882010-02-16 14:50:09 +00001541 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001542 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001543
Chris Lattnerdf986172009-01-02 07:01:27 +00001544 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1545 }
1546 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001547
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001548 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001549}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001550
Chris Lattnerdf986172009-01-02 07:01:27 +00001551/// ParseFunctionType
1552/// ::= Type ArgumentList OptionalAttrs
1553bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1554 assert(Lex.getKind() == lltok::lparen);
1555
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001556 if (!FunctionType::isValidReturnType(Result))
1557 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001558
Chris Lattnerdf986172009-01-02 07:01:27 +00001559 std::vector<ArgInfo> ArgList;
1560 bool isVarArg;
Chris Lattnera16546a2011-06-17 17:37:13 +00001561 if (ParseArgumentList(ArgList, isVarArg, true))
Chris Lattnerdf986172009-01-02 07:01:27 +00001562 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001563
Chris Lattnerdf986172009-01-02 07:01:27 +00001564 // Reject names on the arguments lists.
1565 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1566 if (!ArgList[i].Name.empty())
1567 return Error(ArgList[i].Loc, "argument name invalid in function type");
Chris Lattnera16546a2011-06-17 17:37:13 +00001568 if (ArgList[i].Attrs != 0)
1569 return Error(ArgList[i].Loc,
1570 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001571 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001572
Chris Lattnerdf986172009-01-02 07:01:27 +00001573 std::vector<const Type*> ArgListTy;
1574 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1575 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001576
Owen Andersondebcb012009-07-29 22:17:13 +00001577 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001578 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001579 return false;
1580}
1581
1582/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1583/// TypeRec
1584/// ::= '{' '}'
1585/// ::= '{' TypeRec (',' TypeRec)* '}'
1586/// ::= '<' '{' '}' '>'
1587/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1588bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1589 assert(Lex.getKind() == lltok::lbrace);
1590 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001591
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001592 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001593 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001594 return false;
1595 }
1596
1597 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001598 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001599 if (ParseTypeRec(Result)) return true;
1600 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001601
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001602 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001603 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001604 if (!StructType::isValidElementType(Result))
1605 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001606
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001607 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001608 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001609 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001610
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001611 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001612 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001613 if (!StructType::isValidElementType(Result))
1614 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001615
Chris Lattnerdf986172009-01-02 07:01:27 +00001616 ParamsList.push_back(Result);
1617 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001618
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001619 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1620 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001621
Chris Lattnerdf986172009-01-02 07:01:27 +00001622 std::vector<const Type*> ParamsListTy;
1623 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1624 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001625 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001626 return false;
1627}
1628
1629/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1630/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001631/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001632/// ::= '[' APSINTVAL 'x' Types ']'
1633/// ::= '<' APSINTVAL 'x' Types '>'
1634bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1635 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1636 Lex.getAPSIntVal().getBitWidth() > 64)
1637 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001638
Chris Lattnerdf986172009-01-02 07:01:27 +00001639 LocTy SizeLoc = Lex.getLoc();
1640 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001641 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001642
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001643 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1644 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001645
1646 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001647 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001648 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001649
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001650 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001651 return Error(TypeLoc, "array and vector element type cannot be void");
1652
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001653 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1654 "expected end of sequential type"))
1655 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001656
Chris Lattnerdf986172009-01-02 07:01:27 +00001657 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001658 if (Size == 0)
1659 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001660 if ((unsigned)Size != Size)
1661 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001662 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001663 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001664 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001665 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001666 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001667 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001668 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001669 }
1670 return false;
1671}
1672
1673//===----------------------------------------------------------------------===//
1674// Function Semantic Analysis.
1675//===----------------------------------------------------------------------===//
1676
Chris Lattner09d9ef42009-10-28 03:39:23 +00001677LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1678 int functionNumber)
1679 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001680
1681 // Insert unnamed arguments into the NumberedVals list.
1682 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1683 AI != E; ++AI)
1684 if (!AI->hasName())
1685 NumberedVals.push_back(AI);
1686}
1687
1688LLParser::PerFunctionState::~PerFunctionState() {
1689 // If there were any forward referenced non-basicblock values, delete them.
1690 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1691 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1692 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001693 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001694 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001695 delete I->second.first;
1696 I->second.first = 0;
1697 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001698
Chris Lattnerdf986172009-01-02 07:01:27 +00001699 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1700 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1701 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001702 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001703 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001704 delete I->second.first;
1705 I->second.first = 0;
1706 }
1707}
1708
Chris Lattner09d9ef42009-10-28 03:39:23 +00001709bool LLParser::PerFunctionState::FinishFunction() {
1710 // Check to see if someone took the address of labels in this block.
1711 if (!P.ForwardRefBlockAddresses.empty()) {
1712 ValID FunctionID;
1713 if (!F.getName().empty()) {
1714 FunctionID.Kind = ValID::t_GlobalName;
1715 FunctionID.StrVal = F.getName();
1716 } else {
1717 FunctionID.Kind = ValID::t_GlobalID;
1718 FunctionID.UIntVal = FunctionNumber;
1719 }
1720
1721 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1722 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1723 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1724 // Resolve all these references.
1725 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1726 return true;
1727
1728 P.ForwardRefBlockAddresses.erase(FRBAI);
1729 }
1730 }
1731
Chris Lattnerdf986172009-01-02 07:01:27 +00001732 if (!ForwardRefVals.empty())
1733 return P.Error(ForwardRefVals.begin()->second.second,
1734 "use of undefined value '%" + ForwardRefVals.begin()->first +
1735 "'");
1736 if (!ForwardRefValIDs.empty())
1737 return P.Error(ForwardRefValIDs.begin()->second.second,
1738 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001739 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001740 return false;
1741}
1742
1743
1744/// GetVal - Get a value with the specified name or ID, creating a
1745/// forward reference record if needed. This can return null if the value
1746/// exists but does not have the right type.
1747Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1748 const Type *Ty, LocTy Loc) {
1749 // Look this name up in the normal function symbol table.
1750 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001751
Chris Lattnerdf986172009-01-02 07:01:27 +00001752 // If this is a forward reference for the value, see if we already created a
1753 // forward ref record.
1754 if (Val == 0) {
1755 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1756 I = ForwardRefVals.find(Name);
1757 if (I != ForwardRefVals.end())
1758 Val = I->second.first;
1759 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001760
Chris Lattnerdf986172009-01-02 07:01:27 +00001761 // If we have the value in the symbol table or fwd-ref table, return it.
1762 if (Val) {
1763 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001764 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001765 P.Error(Loc, "'%" + Name + "' is not a basic block");
1766 else
1767 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001768 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001769 return 0;
1770 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001771
Chris Lattnerdf986172009-01-02 07:01:27 +00001772 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001773 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001774 P.Error(Loc, "invalid use of a non-first-class type");
1775 return 0;
1776 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001777
Chris Lattnerdf986172009-01-02 07:01:27 +00001778 // Otherwise, create a new forward reference for this value and remember it.
1779 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001780 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001781 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001782 else
1783 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001784
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1786 return FwdVal;
1787}
1788
1789Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1790 LocTy Loc) {
1791 // Look this name up in the normal function symbol table.
1792 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001793
Chris Lattnerdf986172009-01-02 07:01:27 +00001794 // If this is a forward reference for the value, see if we already created a
1795 // forward ref record.
1796 if (Val == 0) {
1797 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1798 I = ForwardRefValIDs.find(ID);
1799 if (I != ForwardRefValIDs.end())
1800 Val = I->second.first;
1801 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001802
Chris Lattnerdf986172009-01-02 07:01:27 +00001803 // If we have the value in the symbol table or fwd-ref table, return it.
1804 if (Val) {
1805 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001806 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001807 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001808 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001809 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001810 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001811 return 0;
1812 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001813
Duncan Sands47c51882010-02-16 14:50:09 +00001814 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001815 P.Error(Loc, "invalid use of a non-first-class type");
1816 return 0;
1817 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001818
Chris Lattnerdf986172009-01-02 07:01:27 +00001819 // Otherwise, create a new forward reference for this value and remember it.
1820 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001821 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001822 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001823 else
1824 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001825
Chris Lattnerdf986172009-01-02 07:01:27 +00001826 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1827 return FwdVal;
1828}
1829
1830/// SetInstName - After an instruction is parsed and inserted into its
1831/// basic block, this installs its name.
1832bool LLParser::PerFunctionState::SetInstName(int NameID,
1833 const std::string &NameStr,
1834 LocTy NameLoc, Instruction *Inst) {
1835 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001836 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001837 if (NameID != -1 || !NameStr.empty())
1838 return P.Error(NameLoc, "instructions returning void cannot have a name");
1839 return false;
1840 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001841
Chris Lattnerdf986172009-01-02 07:01:27 +00001842 // If this was a numbered instruction, verify that the instruction is the
1843 // expected value and resolve any forward references.
1844 if (NameStr.empty()) {
1845 // If neither a name nor an ID was specified, just use the next ID.
1846 if (NameID == -1)
1847 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001848
Chris Lattnerdf986172009-01-02 07:01:27 +00001849 if (unsigned(NameID) != NumberedVals.size())
1850 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001851 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001852
Chris Lattnerdf986172009-01-02 07:01:27 +00001853 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1854 ForwardRefValIDs.find(NameID);
1855 if (FI != ForwardRefValIDs.end()) {
1856 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001857 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001858 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001859 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001860 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001861 ForwardRefValIDs.erase(FI);
1862 }
1863
1864 NumberedVals.push_back(Inst);
1865 return false;
1866 }
1867
1868 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1869 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1870 FI = ForwardRefVals.find(NameStr);
1871 if (FI != ForwardRefVals.end()) {
1872 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001873 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001874 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001875 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001876 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001877 ForwardRefVals.erase(FI);
1878 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001879
Chris Lattnerdf986172009-01-02 07:01:27 +00001880 // Set the name on the instruction.
1881 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001882
Benjamin Krameraf812352010-10-16 11:28:23 +00001883 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001884 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001885 NameStr + "'");
1886 return false;
1887}
1888
1889/// GetBB - Get a basic block with the specified name or ID, creating a
1890/// forward reference record if needed.
1891BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1892 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001893 return cast_or_null<BasicBlock>(GetVal(Name,
1894 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001895}
1896
1897BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001898 return cast_or_null<BasicBlock>(GetVal(ID,
1899 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001900}
1901
1902/// DefineBB - Define the specified basic block, which is either named or
1903/// unnamed. If there is an error, this returns null otherwise it returns
1904/// the block being defined.
1905BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1906 LocTy Loc) {
1907 BasicBlock *BB;
1908 if (Name.empty())
1909 BB = GetBB(NumberedVals.size(), Loc);
1910 else
1911 BB = GetBB(Name, Loc);
1912 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001913
Chris Lattnerdf986172009-01-02 07:01:27 +00001914 // Move the block to the end of the function. Forward ref'd blocks are
1915 // inserted wherever they happen to be referenced.
1916 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001917
Chris Lattnerdf986172009-01-02 07:01:27 +00001918 // Remove the block from forward ref sets.
1919 if (Name.empty()) {
1920 ForwardRefValIDs.erase(NumberedVals.size());
1921 NumberedVals.push_back(BB);
1922 } else {
1923 // BB forward references are already in the function symbol table.
1924 ForwardRefVals.erase(Name);
1925 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001926
Chris Lattnerdf986172009-01-02 07:01:27 +00001927 return BB;
1928}
1929
1930//===----------------------------------------------------------------------===//
1931// Constants.
1932//===----------------------------------------------------------------------===//
1933
1934/// ParseValID - Parse an abstract value that doesn't necessarily have a
1935/// type implied. For example, if we parse "4" we don't know what integer type
1936/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001937/// sanity. PFS is used to convert function-local operands of metadata (since
1938/// metadata operands are not just parsed here but also converted to values).
1939/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001940bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001941 ID.Loc = Lex.getLoc();
1942 switch (Lex.getKind()) {
1943 default: return TokError("expected value token");
1944 case lltok::GlobalID: // @42
1945 ID.UIntVal = Lex.getUIntVal();
1946 ID.Kind = ValID::t_GlobalID;
1947 break;
1948 case lltok::GlobalVar: // @foo
1949 ID.StrVal = Lex.getStrVal();
1950 ID.Kind = ValID::t_GlobalName;
1951 break;
1952 case lltok::LocalVarID: // %42
1953 ID.UIntVal = Lex.getUIntVal();
1954 ID.Kind = ValID::t_LocalID;
1955 break;
1956 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00001957 ID.StrVal = Lex.getStrVal();
1958 ID.Kind = ValID::t_LocalName;
1959 break;
Dan Gohman83448032010-07-14 18:26:50 +00001960 case lltok::exclaim: // !42, !{...}, or !"foo"
1961 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00001962 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001963 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001964 ID.Kind = ValID::t_APSInt;
1965 break;
1966 case lltok::APFloat:
1967 ID.APFloatVal = Lex.getAPFloatVal();
1968 ID.Kind = ValID::t_APFloat;
1969 break;
1970 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001971 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001972 ID.Kind = ValID::t_Constant;
1973 break;
1974 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001975 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001976 ID.Kind = ValID::t_Constant;
1977 break;
1978 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1979 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1980 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001981
Chris Lattnerdf986172009-01-02 07:01:27 +00001982 case lltok::lbrace: {
1983 // ValID ::= '{' ConstVector '}'
1984 Lex.Lex();
1985 SmallVector<Constant*, 16> Elts;
1986 if (ParseGlobalValueVector(Elts) ||
1987 ParseToken(lltok::rbrace, "expected end of struct constant"))
1988 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001989
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001990 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1991 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001992 ID.Kind = ValID::t_Constant;
1993 return false;
1994 }
1995 case lltok::less: {
1996 // ValID ::= '<' ConstVector '>' --> Vector.
1997 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1998 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001999 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002000
Chris Lattnerdf986172009-01-02 07:01:27 +00002001 SmallVector<Constant*, 16> Elts;
2002 LocTy FirstEltLoc = Lex.getLoc();
2003 if (ParseGlobalValueVector(Elts) ||
2004 (isPackedStruct &&
2005 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2006 ParseToken(lltok::greater, "expected end of constant"))
2007 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002008
Chris Lattnerdf986172009-01-02 07:01:27 +00002009 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002010 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002011 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002012 ID.Kind = ValID::t_Constant;
2013 return false;
2014 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002015
Chris Lattnerdf986172009-01-02 07:01:27 +00002016 if (Elts.empty())
2017 return Error(ID.Loc, "constant vector must not be empty");
2018
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002019 if (!Elts[0]->getType()->isIntegerTy() &&
2020 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002021 return Error(FirstEltLoc,
2022 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002023
Chris Lattnerdf986172009-01-02 07:01:27 +00002024 // Verify that all the vector elements have the same type.
2025 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2026 if (Elts[i]->getType() != Elts[0]->getType())
2027 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002028 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002029 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002030
Chris Lattner2ca5c862011-02-15 00:14:00 +00002031 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002032 ID.Kind = ValID::t_Constant;
2033 return false;
2034 }
2035 case lltok::lsquare: { // Array Constant
2036 Lex.Lex();
2037 SmallVector<Constant*, 16> Elts;
2038 LocTy FirstEltLoc = Lex.getLoc();
2039 if (ParseGlobalValueVector(Elts) ||
2040 ParseToken(lltok::rsquare, "expected end of array constant"))
2041 return true;
2042
2043 // Handle empty element.
2044 if (Elts.empty()) {
2045 // Use undef instead of an array because it's inconvenient to determine
2046 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002047 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002048 return false;
2049 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002050
Chris Lattnerdf986172009-01-02 07:01:27 +00002051 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002052 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002053 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002054
Owen Andersondebcb012009-07-29 22:17:13 +00002055 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002056
Chris Lattnerdf986172009-01-02 07:01:27 +00002057 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002058 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002059 if (Elts[i]->getType() != Elts[0]->getType())
2060 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002061 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002062 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00002063 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002064
Owen Anderson1fd70962009-07-28 18:32:17 +00002065 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 ID.Kind = ValID::t_Constant;
2067 return false;
2068 }
2069 case lltok::kw_c: // c "foo"
2070 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002071 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002072 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2073 ID.Kind = ValID::t_Constant;
2074 return false;
2075
2076 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002077 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2078 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002079 Lex.Lex();
2080 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002081 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002082 ParseStringConstant(ID.StrVal) ||
2083 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002084 ParseToken(lltok::StringConstant, "expected constraint string"))
2085 return true;
2086 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002087 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002088 ID.Kind = ValID::t_InlineAsm;
2089 return false;
2090 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002091
Chris Lattner09d9ef42009-10-28 03:39:23 +00002092 case lltok::kw_blockaddress: {
2093 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2094 Lex.Lex();
2095
2096 ValID Fn, Label;
2097 LocTy FnLoc, LabelLoc;
2098
2099 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2100 ParseValID(Fn) ||
2101 ParseToken(lltok::comma, "expected comma in block address expression")||
2102 ParseValID(Label) ||
2103 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2104 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002105
Chris Lattner09d9ef42009-10-28 03:39:23 +00002106 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2107 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002108 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002109 return Error(Label.Loc, "expected basic block name in blockaddress");
2110
2111 // Make a global variable as a placeholder for this reference.
2112 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2113 false, GlobalValue::InternalLinkage,
2114 0, "");
2115 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2116 ID.ConstantVal = FwdRef;
2117 ID.Kind = ValID::t_Constant;
2118 return false;
2119 }
2120
Chris Lattnerdf986172009-01-02 07:01:27 +00002121 case lltok::kw_trunc:
2122 case lltok::kw_zext:
2123 case lltok::kw_sext:
2124 case lltok::kw_fptrunc:
2125 case lltok::kw_fpext:
2126 case lltok::kw_bitcast:
2127 case lltok::kw_uitofp:
2128 case lltok::kw_sitofp:
2129 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002130 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002131 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002132 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002133 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002134 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002135 Constant *SrcVal;
2136 Lex.Lex();
2137 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2138 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002139 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002140 ParseType(DestTy) ||
2141 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2142 return true;
2143 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2144 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002145 getTypeString(SrcVal->getType()) + "' to '" +
2146 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002147 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002148 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002149 ID.Kind = ValID::t_Constant;
2150 return false;
2151 }
2152 case lltok::kw_extractvalue: {
2153 Lex.Lex();
2154 Constant *Val;
2155 SmallVector<unsigned, 4> Indices;
2156 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2157 ParseGlobalTypeAndValue(Val) ||
2158 ParseIndexList(Indices) ||
2159 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2160 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002161
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002162 if (!Val->getType()->isAggregateType())
2163 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002164 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2165 Indices.end()))
2166 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002167 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002168 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002169 ID.Kind = ValID::t_Constant;
2170 return false;
2171 }
2172 case lltok::kw_insertvalue: {
2173 Lex.Lex();
2174 Constant *Val0, *Val1;
2175 SmallVector<unsigned, 4> Indices;
2176 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2177 ParseGlobalTypeAndValue(Val0) ||
2178 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2179 ParseGlobalTypeAndValue(Val1) ||
2180 ParseIndexList(Indices) ||
2181 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2182 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002183 if (!Val0->getType()->isAggregateType())
2184 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002185 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2186 Indices.end()))
2187 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002188 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002189 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002190 ID.Kind = ValID::t_Constant;
2191 return false;
2192 }
2193 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002194 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002195 unsigned PredVal, Opc = Lex.getUIntVal();
2196 Constant *Val0, *Val1;
2197 Lex.Lex();
2198 if (ParseCmpPredicate(PredVal, Opc) ||
2199 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2200 ParseGlobalTypeAndValue(Val0) ||
2201 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2202 ParseGlobalTypeAndValue(Val1) ||
2203 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2204 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002205
Chris Lattnerdf986172009-01-02 07:01:27 +00002206 if (Val0->getType() != Val1->getType())
2207 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002208
Chris Lattnerdf986172009-01-02 07:01:27 +00002209 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002210
Chris Lattnerdf986172009-01-02 07:01:27 +00002211 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002212 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002213 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002214 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002215 } else {
2216 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002217 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002218 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002219 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002220 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002221 }
2222 ID.Kind = ValID::t_Constant;
2223 return false;
2224 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002225
Chris Lattnerdf986172009-01-02 07:01:27 +00002226 // Binary Operators.
2227 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002228 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002229 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002230 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002231 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002232 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002233 case lltok::kw_udiv:
2234 case lltok::kw_sdiv:
2235 case lltok::kw_fdiv:
2236 case lltok::kw_urem:
2237 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002238 case lltok::kw_frem:
2239 case lltok::kw_shl:
2240 case lltok::kw_lshr:
2241 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002242 bool NUW = false;
2243 bool NSW = false;
2244 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002245 unsigned Opc = Lex.getUIntVal();
2246 Constant *Val0, *Val1;
2247 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002248 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002249 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2250 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002251 if (EatIfPresent(lltok::kw_nuw))
2252 NUW = true;
2253 if (EatIfPresent(lltok::kw_nsw)) {
2254 NSW = true;
2255 if (EatIfPresent(lltok::kw_nuw))
2256 NUW = true;
2257 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002258 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2259 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002260 if (EatIfPresent(lltok::kw_exact))
2261 Exact = true;
2262 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002263 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2264 ParseGlobalTypeAndValue(Val0) ||
2265 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2266 ParseGlobalTypeAndValue(Val1) ||
2267 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2268 return true;
2269 if (Val0->getType() != Val1->getType())
2270 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002271 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002272 if (NUW)
2273 return Error(ModifierLoc, "nuw only applies to integer operations");
2274 if (NSW)
2275 return Error(ModifierLoc, "nsw only applies to integer operations");
2276 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002277 // Check that the type is valid for the operator.
2278 switch (Opc) {
2279 case Instruction::Add:
2280 case Instruction::Sub:
2281 case Instruction::Mul:
2282 case Instruction::UDiv:
2283 case Instruction::SDiv:
2284 case Instruction::URem:
2285 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002286 case Instruction::Shl:
2287 case Instruction::AShr:
2288 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002289 if (!Val0->getType()->isIntOrIntVectorTy())
2290 return Error(ID.Loc, "constexpr requires integer operands");
2291 break;
2292 case Instruction::FAdd:
2293 case Instruction::FSub:
2294 case Instruction::FMul:
2295 case Instruction::FDiv:
2296 case Instruction::FRem:
2297 if (!Val0->getType()->isFPOrFPVectorTy())
2298 return Error(ID.Loc, "constexpr requires fp operands");
2299 break;
2300 default: llvm_unreachable("Unknown binary operator!");
2301 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002302 unsigned Flags = 0;
2303 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2304 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002305 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002306 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002307 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002308 ID.Kind = ValID::t_Constant;
2309 return false;
2310 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002311
Chris Lattnerdf986172009-01-02 07:01:27 +00002312 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002313 case lltok::kw_and:
2314 case lltok::kw_or:
2315 case lltok::kw_xor: {
2316 unsigned Opc = Lex.getUIntVal();
2317 Constant *Val0, *Val1;
2318 Lex.Lex();
2319 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2320 ParseGlobalTypeAndValue(Val0) ||
2321 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2322 ParseGlobalTypeAndValue(Val1) ||
2323 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2324 return true;
2325 if (Val0->getType() != Val1->getType())
2326 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002327 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002328 return Error(ID.Loc,
2329 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002330 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002331 ID.Kind = ValID::t_Constant;
2332 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002333 }
2334
Chris Lattnerdf986172009-01-02 07:01:27 +00002335 case lltok::kw_getelementptr:
2336 case lltok::kw_shufflevector:
2337 case lltok::kw_insertelement:
2338 case lltok::kw_extractelement:
2339 case lltok::kw_select: {
2340 unsigned Opc = Lex.getUIntVal();
2341 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002342 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002343 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002344 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002345 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002346 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2347 ParseGlobalValueVector(Elts) ||
2348 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2349 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002350
Chris Lattnerdf986172009-01-02 07:01:27 +00002351 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002352 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002353 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002354
Chris Lattnerdf986172009-01-02 07:01:27 +00002355 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002356 (Value**)(Elts.data() + 1),
2357 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002358 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002359 ID.ConstantVal = InBounds ?
2360 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2361 Elts.data() + 1,
2362 Elts.size() - 1) :
2363 ConstantExpr::getGetElementPtr(Elts[0],
2364 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002365 } else if (Opc == Instruction::Select) {
2366 if (Elts.size() != 3)
2367 return Error(ID.Loc, "expected three operands to select");
2368 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2369 Elts[2]))
2370 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002371 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002372 } else if (Opc == Instruction::ShuffleVector) {
2373 if (Elts.size() != 3)
2374 return Error(ID.Loc, "expected three operands to shufflevector");
2375 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2376 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002377 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002378 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002379 } else if (Opc == Instruction::ExtractElement) {
2380 if (Elts.size() != 2)
2381 return Error(ID.Loc, "expected two operands to extractelement");
2382 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2383 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002384 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002385 } else {
2386 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2387 if (Elts.size() != 3)
2388 return Error(ID.Loc, "expected three operands to insertelement");
2389 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2390 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002391 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002392 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002393 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002394
Chris Lattnerdf986172009-01-02 07:01:27 +00002395 ID.Kind = ValID::t_Constant;
2396 return false;
2397 }
2398 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002399
Chris Lattnerdf986172009-01-02 07:01:27 +00002400 Lex.Lex();
2401 return false;
2402}
2403
2404/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002405bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2406 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002407 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002408 Value *V = NULL;
2409 bool Parsed = ParseValID(ID) ||
2410 ConvertValIDToValue(Ty, ID, V, NULL);
2411 if (V && !(C = dyn_cast<Constant>(V)))
2412 return Error(ID.Loc, "global values must be constants");
2413 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002414}
2415
Victor Hernandez92f238d2010-01-11 22:31:58 +00002416bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2417 PATypeHolder Type(Type::getVoidTy(Context));
2418 return ParseType(Type) ||
2419 ParseGlobalValue(Type, V);
2420}
2421
2422/// ParseGlobalValueVector
2423/// ::= /*empty*/
2424/// ::= TypeAndValue (',' TypeAndValue)*
2425bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2426 // Empty list.
2427 if (Lex.getKind() == lltok::rbrace ||
2428 Lex.getKind() == lltok::rsquare ||
2429 Lex.getKind() == lltok::greater ||
2430 Lex.getKind() == lltok::rparen)
2431 return false;
2432
2433 Constant *C;
2434 if (ParseGlobalTypeAndValue(C)) return true;
2435 Elts.push_back(C);
2436
2437 while (EatIfPresent(lltok::comma)) {
2438 if (ParseGlobalTypeAndValue(C)) return true;
2439 Elts.push_back(C);
2440 }
2441
2442 return false;
2443}
2444
Dan Gohman309b3af2010-08-24 02:24:03 +00002445bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2446 assert(Lex.getKind() == lltok::lbrace);
2447 Lex.Lex();
2448
2449 SmallVector<Value*, 16> Elts;
2450 if (ParseMDNodeVector(Elts, PFS) ||
2451 ParseToken(lltok::rbrace, "expected end of metadata node"))
2452 return true;
2453
Jay Foadec9186b2011-04-21 19:59:31 +00002454 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002455 ID.Kind = ValID::t_MDNode;
2456 return false;
2457}
2458
Dan Gohman83448032010-07-14 18:26:50 +00002459/// ParseMetadataValue
2460/// ::= !42
2461/// ::= !{...}
2462/// ::= !"string"
2463bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2464 assert(Lex.getKind() == lltok::exclaim);
2465 Lex.Lex();
2466
2467 // MDNode:
2468 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002469 if (Lex.getKind() == lltok::lbrace)
2470 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002471
2472 // Standalone metadata reference
2473 // !42
2474 if (Lex.getKind() == lltok::APSInt) {
2475 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2476 ID.Kind = ValID::t_MDNode;
2477 return false;
2478 }
2479
2480 // MDString:
2481 // ::= '!' STRINGCONSTANT
2482 if (ParseMDString(ID.MDStringVal)) return true;
2483 ID.Kind = ValID::t_MDString;
2484 return false;
2485}
2486
Victor Hernandez92f238d2010-01-11 22:31:58 +00002487
2488//===----------------------------------------------------------------------===//
2489// Function Parsing.
2490//===----------------------------------------------------------------------===//
2491
2492bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2493 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002494 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002495 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002496
Chris Lattnerdf986172009-01-02 07:01:27 +00002497 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002498 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002499 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002500 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2501 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2502 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002503 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002504 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2505 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2506 return (V == 0);
2507 case ValID::t_InlineAsm: {
2508 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2509 const FunctionType *FTy =
2510 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2511 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2512 return Error(ID.Loc, "invalid type for inline asm constraint string");
2513 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2514 return false;
2515 }
2516 case ValID::t_MDNode:
2517 if (!Ty->isMetadataTy())
2518 return Error(ID.Loc, "metadata value must have metadata type");
2519 V = ID.MDNodeVal;
2520 return false;
2521 case ValID::t_MDString:
2522 if (!Ty->isMetadataTy())
2523 return Error(ID.Loc, "metadata value must have metadata type");
2524 V = ID.MDStringVal;
2525 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002526 case ValID::t_GlobalName:
2527 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2528 return V == 0;
2529 case ValID::t_GlobalID:
2530 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2531 return V == 0;
2532 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002533 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002534 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002535 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002536 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002537 return false;
2538 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002539 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002540 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2541 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002542
Chris Lattnerdf986172009-01-02 07:01:27 +00002543 // The lexer has no type info, so builds all float and double FP constants
2544 // as double. Fix this here. Long double does not need this.
2545 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002546 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002547 bool Ignored;
2548 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2549 &Ignored);
2550 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002551 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002552
Chris Lattner959873d2009-01-05 18:24:23 +00002553 if (V->getType() != Ty)
2554 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002555 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002556
Chris Lattnerdf986172009-01-02 07:01:27 +00002557 return false;
2558 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002559 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002560 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002561 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002562 return false;
2563 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002564 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002565 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002566 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002567 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002568 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002569 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002570 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002571 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002572 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002573 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002574 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002575 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002576 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002577 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002578 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002579 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002580 return false;
2581 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002582 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002583 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002584
Chris Lattnerdf986172009-01-02 07:01:27 +00002585 V = ID.ConstantVal;
2586 return false;
2587 }
2588}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002589
Chris Lattnerdf986172009-01-02 07:01:27 +00002590bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2591 V = 0;
2592 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002593 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002594 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002595}
2596
2597bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002598 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002599 return ParseType(T) ||
2600 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002601}
2602
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002603bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2604 PerFunctionState &PFS) {
2605 Value *V;
2606 Loc = Lex.getLoc();
2607 if (ParseTypeAndValue(V, PFS)) return true;
2608 if (!isa<BasicBlock>(V))
2609 return Error(Loc, "expected a basic block");
2610 BB = cast<BasicBlock>(V);
2611 return false;
2612}
2613
2614
Chris Lattnerdf986172009-01-02 07:01:27 +00002615/// FunctionHeader
2616/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002617/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002618/// OptionalAlign OptGC
2619bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2620 // Parse the linkage.
2621 LocTy LinkageLoc = Lex.getLoc();
2622 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002623
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002624 unsigned Visibility, RetAttrs;
2625 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002626 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002627 LocTy RetTypeLoc = Lex.getLoc();
2628 if (ParseOptionalLinkage(Linkage) ||
2629 ParseOptionalVisibility(Visibility) ||
2630 ParseOptionalCallingConv(CC) ||
2631 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002632 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002633 return true;
2634
2635 // Verify that the linkage is ok.
2636 switch ((GlobalValue::LinkageTypes)Linkage) {
2637 case GlobalValue::ExternalLinkage:
2638 break; // always ok.
2639 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002640 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002641 if (isDefine)
2642 return Error(LinkageLoc, "invalid linkage for function definition");
2643 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002644 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002645 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002646 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002647 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002648 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002649 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002650 case GlobalValue::LinkOnceAnyLinkage:
2651 case GlobalValue::LinkOnceODRLinkage:
2652 case GlobalValue::WeakAnyLinkage:
2653 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002654 case GlobalValue::DLLExportLinkage:
2655 if (!isDefine)
2656 return Error(LinkageLoc, "invalid linkage for function declaration");
2657 break;
2658 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002659 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002660 return Error(LinkageLoc, "invalid function linkage type");
2661 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002662
Chris Lattner99bb3152009-01-05 08:00:30 +00002663 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002664 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002665 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002666
Chris Lattnerdf986172009-01-02 07:01:27 +00002667 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002668
2669 std::string FunctionName;
2670 if (Lex.getKind() == lltok::GlobalVar) {
2671 FunctionName = Lex.getStrVal();
2672 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2673 unsigned NameID = Lex.getUIntVal();
2674
2675 if (NameID != NumberedVals.size())
2676 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002677 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002678 } else {
2679 return TokError("expected function name");
2680 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002681
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002682 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002683
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002684 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002685 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002686
Chris Lattnerdf986172009-01-02 07:01:27 +00002687 std::vector<ArgInfo> ArgList;
2688 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002689 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002690 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002691 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002692 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002693 bool UnnamedAddr;
2694 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002695
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002696 if (ParseArgumentList(ArgList, isVarArg, false) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002697 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2698 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002699 ParseOptionalAttrs(FuncAttrs, 2) ||
2700 (EatIfPresent(lltok::kw_section) &&
2701 ParseStringConstant(Section)) ||
2702 ParseOptionalAlignment(Alignment) ||
2703 (EatIfPresent(lltok::kw_gc) &&
2704 ParseStringConstant(GC)))
2705 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002706
2707 // If the alignment was parsed as an attribute, move to the alignment field.
2708 if (FuncAttrs & Attribute::Alignment) {
2709 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2710 FuncAttrs &= ~Attribute::Alignment;
2711 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002712
Chris Lattnerdf986172009-01-02 07:01:27 +00002713 // Okay, if we got here, the function is syntactically valid. Convert types
2714 // and do semantic checks.
2715 std::vector<const Type*> ParamTypeList;
2716 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002717
Chris Lattnerdf986172009-01-02 07:01:27 +00002718 if (RetAttrs != Attribute::None)
2719 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002720
Chris Lattnerdf986172009-01-02 07:01:27 +00002721 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2722 ParamTypeList.push_back(ArgList[i].Type);
2723 if (ArgList[i].Attrs != Attribute::None)
2724 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2725 }
2726
2727 if (FuncAttrs != Attribute::None)
2728 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2729
2730 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002731
Benjamin Kramerf0127052010-01-05 13:12:22 +00002732 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002733 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2734
Owen Andersonfba933c2009-07-01 23:57:11 +00002735 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002736 FunctionType::get(RetType, ParamTypeList, isVarArg);
2737 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002738
2739 Fn = 0;
2740 if (!FunctionName.empty()) {
2741 // If this was a definition of a forward reference, remove the definition
2742 // from the forward reference table and fill in the forward ref.
2743 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2744 ForwardRefVals.find(FunctionName);
2745 if (FRVI != ForwardRefVals.end()) {
2746 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002747 if (Fn->getType() != PFT)
2748 return Error(FRVI->second.second, "invalid forward reference to "
2749 "function '" + FunctionName + "' with wrong type!");
2750
Chris Lattnerdf986172009-01-02 07:01:27 +00002751 ForwardRefVals.erase(FRVI);
2752 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002753 // Reject redefinitions.
2754 return Error(NameLoc, "invalid redefinition of function '" +
2755 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002756 } else if (M->getNamedValue(FunctionName)) {
2757 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002759
Dan Gohman41905542009-08-29 23:37:49 +00002760 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002761 // If this is a definition of a forward referenced function, make sure the
2762 // types agree.
2763 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2764 = ForwardRefValIDs.find(NumberedVals.size());
2765 if (I != ForwardRefValIDs.end()) {
2766 Fn = cast<Function>(I->second.first);
2767 if (Fn->getType() != PFT)
2768 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002769 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002770 ForwardRefValIDs.erase(I);
2771 }
2772 }
2773
2774 if (Fn == 0)
2775 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2776 else // Move the forward-reference to the correct spot in the module.
2777 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2778
2779 if (FunctionName.empty())
2780 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002781
Chris Lattnerdf986172009-01-02 07:01:27 +00002782 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2783 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2784 Fn->setCallingConv(CC);
2785 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002786 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002787 Fn->setAlignment(Alignment);
2788 Fn->setSection(Section);
2789 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002790
Chris Lattnerdf986172009-01-02 07:01:27 +00002791 // Add all of the arguments we parsed to the function.
2792 Function::arg_iterator ArgIt = Fn->arg_begin();
2793 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2794 // If the argument has a name, insert it into the argument symbol table.
2795 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002796
Chris Lattnerdf986172009-01-02 07:01:27 +00002797 // Set the name, if it conflicted, it will be auto-renamed.
2798 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002799
Benjamin Krameraf812352010-10-16 11:28:23 +00002800 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002801 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2802 ArgList[i].Name + "'");
2803 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002804
Chris Lattnerdf986172009-01-02 07:01:27 +00002805 return false;
2806}
2807
2808
2809/// ParseFunctionBody
2810/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002811///
2812bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002813 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002814 return TokError("expected '{' in function body");
2815 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002816
Chris Lattner09d9ef42009-10-28 03:39:23 +00002817 int FunctionNumber = -1;
2818 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2819
2820 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002821
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002822 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002823 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002824 return TokError("function body requires at least one basic block");
2825
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002826 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002827 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002828
Chris Lattnerdf986172009-01-02 07:01:27 +00002829 // Eat the }.
2830 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002831
Chris Lattnerdf986172009-01-02 07:01:27 +00002832 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002833 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002834}
2835
2836/// ParseBasicBlock
2837/// ::= LabelStr? Instruction*
2838bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2839 // If this basic block starts out with a name, remember it.
2840 std::string Name;
2841 LocTy NameLoc = Lex.getLoc();
2842 if (Lex.getKind() == lltok::LabelStr) {
2843 Name = Lex.getStrVal();
2844 Lex.Lex();
2845 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002846
Chris Lattnerdf986172009-01-02 07:01:27 +00002847 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2848 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002849
Chris Lattnerdf986172009-01-02 07:01:27 +00002850 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002851
Chris Lattnerdf986172009-01-02 07:01:27 +00002852 // Parse the instructions in this block until we get a terminator.
2853 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002854 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002855 do {
2856 // This instruction may have three possibilities for a name: a) none
2857 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2858 LocTy NameLoc = Lex.getLoc();
2859 int NameID = -1;
2860 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002861
Chris Lattnerdf986172009-01-02 07:01:27 +00002862 if (Lex.getKind() == lltok::LocalVarID) {
2863 NameID = Lex.getUIntVal();
2864 Lex.Lex();
2865 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2866 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002867 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002868 NameStr = Lex.getStrVal();
2869 Lex.Lex();
2870 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2871 return true;
2872 }
Devang Patelf633a062009-09-17 23:04:48 +00002873
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002874 switch (ParseInstruction(Inst, BB, PFS)) {
2875 default: assert(0 && "Unknown ParseInstruction result!");
2876 case InstError: return true;
2877 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002878 BB->getInstList().push_back(Inst);
2879
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002880 // With a normal result, we check to see if the instruction is followed by
2881 // a comma and metadata.
2882 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002883 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002884 return true;
2885 break;
2886 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002887 BB->getInstList().push_back(Inst);
2888
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002889 // If the instruction parser ate an extra comma at the end of it, it
2890 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002891 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002892 return true;
2893 break;
2894 }
Devang Patelf633a062009-09-17 23:04:48 +00002895
Chris Lattnerdf986172009-01-02 07:01:27 +00002896 // Set the name on the instruction.
2897 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2898 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002899
Chris Lattnerdf986172009-01-02 07:01:27 +00002900 return false;
2901}
2902
2903//===----------------------------------------------------------------------===//
2904// Instruction Parsing.
2905//===----------------------------------------------------------------------===//
2906
2907/// ParseInstruction - Parse one of the many different instructions.
2908///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002909int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2910 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002911 lltok::Kind Token = Lex.getKind();
2912 if (Token == lltok::Eof)
2913 return TokError("found end of file when expecting more instructions");
2914 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002915 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002916 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002917
Chris Lattnerdf986172009-01-02 07:01:27 +00002918 switch (Token) {
2919 default: return Error(Loc, "expected instruction opcode");
2920 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002921 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2922 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002923 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2924 case lltok::kw_br: return ParseBr(Inst, PFS);
2925 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002926 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002927 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2928 // Binary Operators.
2929 case lltok::kw_add:
2930 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00002931 case lltok::kw_mul:
2932 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00002933 bool NUW = EatIfPresent(lltok::kw_nuw);
2934 bool NSW = EatIfPresent(lltok::kw_nsw);
2935 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2936
2937 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2938
2939 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2940 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2941 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002942 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002943 case lltok::kw_fadd:
2944 case lltok::kw_fsub:
2945 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2946
Chris Lattner35bda892011-02-06 21:44:57 +00002947 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00002948 case lltok::kw_udiv:
2949 case lltok::kw_lshr:
2950 case lltok::kw_ashr: {
2951 bool Exact = EatIfPresent(lltok::kw_exact);
2952
2953 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2954 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2955 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002956 }
2957
Chris Lattnerdf986172009-01-02 07:01:27 +00002958 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002959 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002960 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002961 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002962 case lltok::kw_and:
2963 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002964 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002965 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002966 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002967 // Casts.
2968 case lltok::kw_trunc:
2969 case lltok::kw_zext:
2970 case lltok::kw_sext:
2971 case lltok::kw_fptrunc:
2972 case lltok::kw_fpext:
2973 case lltok::kw_bitcast:
2974 case lltok::kw_uitofp:
2975 case lltok::kw_sitofp:
2976 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002977 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002978 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002979 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002980 // Other.
2981 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002982 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002983 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2984 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2985 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2986 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2987 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2988 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2989 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002990 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002991 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2992 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2993 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002994 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002995 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002996 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002997 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002998 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002999 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003000 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3001 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3002 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3003 }
3004}
3005
3006/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3007bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003008 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003009 switch (Lex.getKind()) {
3010 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3011 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3012 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3013 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3014 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3015 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3016 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3017 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3018 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3019 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3020 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3021 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3022 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3023 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3024 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3025 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3026 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3027 }
3028 } else {
3029 switch (Lex.getKind()) {
3030 default: TokError("expected icmp predicate (e.g. 'eq')");
3031 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3032 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3033 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3034 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3035 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3036 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3037 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3038 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3039 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3040 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3041 }
3042 }
3043 Lex.Lex();
3044 return false;
3045}
3046
3047//===----------------------------------------------------------------------===//
3048// Terminator Instructions.
3049//===----------------------------------------------------------------------===//
3050
3051/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003052/// ::= 'ret' void (',' !dbg, !1)*
3053/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003054bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003055 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003056 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003057 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003058
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003059 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003060 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003061 return false;
3062 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003063
Chris Lattnerdf986172009-01-02 07:01:27 +00003064 Value *RV;
3065 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003066
Owen Anderson1d0be152009-08-13 21:58:54 +00003067 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003068 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003069}
3070
3071
3072/// ParseBr
3073/// ::= 'br' TypeAndValue
3074/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3075bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3076 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003077 Value *Op0;
3078 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003079 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003080
Chris Lattnerdf986172009-01-02 07:01:27 +00003081 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3082 Inst = BranchInst::Create(BB);
3083 return false;
3084 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003085
Owen Anderson1d0be152009-08-13 21:58:54 +00003086 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003087 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003088
Chris Lattnerdf986172009-01-02 07:01:27 +00003089 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003090 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003091 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003092 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003093 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003094
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003095 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003096 return false;
3097}
3098
3099/// ParseSwitch
3100/// Instruction
3101/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3102/// JumpTable
3103/// ::= (TypeAndValue ',' TypeAndValue)*
3104bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3105 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003106 Value *Cond;
3107 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003108 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3109 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003110 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003111 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3112 return true;
3113
Duncan Sands1df98592010-02-16 11:11:14 +00003114 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003115 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003116
Chris Lattnerdf986172009-01-02 07:01:27 +00003117 // Parse the jump table pairs.
3118 SmallPtrSet<Value*, 32> SeenCases;
3119 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3120 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003121 Value *Constant;
3122 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003123
Chris Lattnerdf986172009-01-02 07:01:27 +00003124 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3125 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003126 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003127 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003128
Chris Lattnerdf986172009-01-02 07:01:27 +00003129 if (!SeenCases.insert(Constant))
3130 return Error(CondLoc, "duplicate case value in switch");
3131 if (!isa<ConstantInt>(Constant))
3132 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003133
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003134 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003135 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003136
Chris Lattnerdf986172009-01-02 07:01:27 +00003137 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003138
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003139 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003140 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3141 SI->addCase(Table[i].first, Table[i].second);
3142 Inst = SI;
3143 return false;
3144}
3145
Chris Lattnerab21db72009-10-28 00:19:10 +00003146/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003147/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003148/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3149bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003150 LocTy AddrLoc;
3151 Value *Address;
3152 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003153 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3154 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003155 return true;
3156
Duncan Sands1df98592010-02-16 11:11:14 +00003157 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003158 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003159
3160 // Parse the destination list.
3161 SmallVector<BasicBlock*, 16> DestList;
3162
3163 if (Lex.getKind() != lltok::rsquare) {
3164 BasicBlock *DestBB;
3165 if (ParseTypeAndBasicBlock(DestBB, PFS))
3166 return true;
3167 DestList.push_back(DestBB);
3168
3169 while (EatIfPresent(lltok::comma)) {
3170 if (ParseTypeAndBasicBlock(DestBB, PFS))
3171 return true;
3172 DestList.push_back(DestBB);
3173 }
3174 }
3175
3176 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3177 return true;
3178
Chris Lattnerab21db72009-10-28 00:19:10 +00003179 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003180 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3181 IBI->addDestination(DestList[i]);
3182 Inst = IBI;
3183 return false;
3184}
3185
3186
Chris Lattnerdf986172009-01-02 07:01:27 +00003187/// ParseInvoke
3188/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3189/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3190bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3191 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003192 unsigned RetAttrs, FnAttrs;
3193 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003194 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003195 LocTy RetTypeLoc;
3196 ValID CalleeID;
3197 SmallVector<ParamInfo, 16> ArgList;
3198
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003199 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003200 if (ParseOptionalCallingConv(CC) ||
3201 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003202 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003203 ParseValID(CalleeID) ||
3204 ParseParameterList(ArgList, PFS) ||
3205 ParseOptionalAttrs(FnAttrs, 2) ||
3206 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003207 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003208 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003209 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003210 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003211
Chris Lattnerdf986172009-01-02 07:01:27 +00003212 // If RetType is a non-function pointer type, then this is the short syntax
3213 // for the call, which means that RetType is just the return type. Infer the
3214 // rest of the function argument types from the arguments that are present.
3215 const PointerType *PFTy = 0;
3216 const FunctionType *Ty = 0;
3217 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3218 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3219 // Pull out the types of all of the arguments...
3220 std::vector<const Type*> ParamTypes;
3221 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3222 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003223
Chris Lattnerdf986172009-01-02 07:01:27 +00003224 if (!FunctionType::isValidReturnType(RetType))
3225 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003226
Owen Andersondebcb012009-07-29 22:17:13 +00003227 Ty = FunctionType::get(RetType, ParamTypes, false);
3228 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003229 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003230
Chris Lattnerdf986172009-01-02 07:01:27 +00003231 // Look up the callee.
3232 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003233 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003234
Chris Lattnerdf986172009-01-02 07:01:27 +00003235 // Set up the Attributes for the function.
3236 SmallVector<AttributeWithIndex, 8> Attrs;
3237 if (RetAttrs != Attribute::None)
3238 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003239
Chris Lattnerdf986172009-01-02 07:01:27 +00003240 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003241
Chris Lattnerdf986172009-01-02 07:01:27 +00003242 // Loop through FunctionType's arguments and ensure they are specified
3243 // correctly. Also, gather any parameter attributes.
3244 FunctionType::param_iterator I = Ty->param_begin();
3245 FunctionType::param_iterator E = Ty->param_end();
3246 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3247 const Type *ExpectedTy = 0;
3248 if (I != E) {
3249 ExpectedTy = *I++;
3250 } else if (!Ty->isVarArg()) {
3251 return Error(ArgList[i].Loc, "too many arguments specified");
3252 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003253
Chris Lattnerdf986172009-01-02 07:01:27 +00003254 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3255 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003256 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003257 Args.push_back(ArgList[i].V);
3258 if (ArgList[i].Attrs != Attribute::None)
3259 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3260 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003261
Chris Lattnerdf986172009-01-02 07:01:27 +00003262 if (I != E)
3263 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003264
Chris Lattnerdf986172009-01-02 07:01:27 +00003265 if (FnAttrs != Attribute::None)
3266 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003267
Chris Lattnerdf986172009-01-02 07:01:27 +00003268 // Finish off the Attributes and check them
3269 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003270
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003271 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003272 Args.begin(), Args.end());
3273 II->setCallingConv(CC);
3274 II->setAttributes(PAL);
3275 Inst = II;
3276 return false;
3277}
3278
3279
3280
3281//===----------------------------------------------------------------------===//
3282// Binary Operators.
3283//===----------------------------------------------------------------------===//
3284
3285/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003286/// ::= ArithmeticOps TypeAndValue ',' Value
3287///
3288/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3289/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003290bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003291 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003292 LocTy Loc; Value *LHS, *RHS;
3293 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3294 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3295 ParseValue(LHS->getType(), RHS, PFS))
3296 return true;
3297
Chris Lattnere914b592009-01-05 08:24:46 +00003298 bool Valid;
3299 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003300 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003301 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003302 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3303 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003304 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003305 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3306 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003307 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003308
Chris Lattnere914b592009-01-05 08:24:46 +00003309 if (!Valid)
3310 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003311
Chris Lattnerdf986172009-01-02 07:01:27 +00003312 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3313 return false;
3314}
3315
3316/// ParseLogical
3317/// ::= ArithmeticOps TypeAndValue ',' Value {
3318bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3319 unsigned Opc) {
3320 LocTy Loc; Value *LHS, *RHS;
3321 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3322 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3323 ParseValue(LHS->getType(), RHS, PFS))
3324 return true;
3325
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003326 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003327 return Error(Loc,"instruction requires integer or integer vector operands");
3328
3329 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3330 return false;
3331}
3332
3333
3334/// ParseCompare
3335/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3336/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003337bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3338 unsigned Opc) {
3339 // Parse the integer/fp comparison predicate.
3340 LocTy Loc;
3341 unsigned Pred;
3342 Value *LHS, *RHS;
3343 if (ParseCmpPredicate(Pred, Opc) ||
3344 ParseTypeAndValue(LHS, Loc, PFS) ||
3345 ParseToken(lltok::comma, "expected ',' after compare value") ||
3346 ParseValue(LHS->getType(), RHS, PFS))
3347 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003348
Chris Lattnerdf986172009-01-02 07:01:27 +00003349 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003350 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003351 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003352 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003353 } else {
3354 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003355 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003356 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003357 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003358 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003359 }
3360 return false;
3361}
3362
3363//===----------------------------------------------------------------------===//
3364// Other Instructions.
3365//===----------------------------------------------------------------------===//
3366
3367
3368/// ParseCast
3369/// ::= CastOpc TypeAndValue 'to' Type
3370bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3371 unsigned Opc) {
3372 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003373 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003374 if (ParseTypeAndValue(Op, Loc, PFS) ||
3375 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3376 ParseType(DestTy))
3377 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003378
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003379 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3380 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003381 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003382 getTypeString(Op->getType()) + "' to '" +
3383 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003384 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003385 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3386 return false;
3387}
3388
3389/// ParseSelect
3390/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3391bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3392 LocTy Loc;
3393 Value *Op0, *Op1, *Op2;
3394 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3395 ParseToken(lltok::comma, "expected ',' after select condition") ||
3396 ParseTypeAndValue(Op1, PFS) ||
3397 ParseToken(lltok::comma, "expected ',' after select value") ||
3398 ParseTypeAndValue(Op2, PFS))
3399 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003400
Chris Lattnerdf986172009-01-02 07:01:27 +00003401 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3402 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003403
Chris Lattnerdf986172009-01-02 07:01:27 +00003404 Inst = SelectInst::Create(Op0, Op1, Op2);
3405 return false;
3406}
3407
Chris Lattner0088a5c2009-01-05 08:18:44 +00003408/// ParseVA_Arg
3409/// ::= 'va_arg' TypeAndValue ',' Type
3410bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003411 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003412 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003413 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003414 if (ParseTypeAndValue(Op, PFS) ||
3415 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003416 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003417 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003418
Chris Lattner0088a5c2009-01-05 08:18:44 +00003419 if (!EltTy->isFirstClassType())
3420 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003421
3422 Inst = new VAArgInst(Op, EltTy);
3423 return false;
3424}
3425
3426/// ParseExtractElement
3427/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3428bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3429 LocTy Loc;
3430 Value *Op0, *Op1;
3431 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3432 ParseToken(lltok::comma, "expected ',' after extract value") ||
3433 ParseTypeAndValue(Op1, PFS))
3434 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003435
Chris Lattnerdf986172009-01-02 07:01:27 +00003436 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3437 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003438
Eric Christophera3500da2009-07-25 02:28:41 +00003439 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003440 return false;
3441}
3442
3443/// ParseInsertElement
3444/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3445bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3446 LocTy Loc;
3447 Value *Op0, *Op1, *Op2;
3448 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3449 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3450 ParseTypeAndValue(Op1, PFS) ||
3451 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3452 ParseTypeAndValue(Op2, PFS))
3453 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003454
Chris Lattnerdf986172009-01-02 07:01:27 +00003455 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003456 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003457
Chris Lattnerdf986172009-01-02 07:01:27 +00003458 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3459 return false;
3460}
3461
3462/// ParseShuffleVector
3463/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3464bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3465 LocTy Loc;
3466 Value *Op0, *Op1, *Op2;
3467 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3468 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3469 ParseTypeAndValue(Op1, PFS) ||
3470 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3471 ParseTypeAndValue(Op2, PFS))
3472 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003473
Chris Lattnerdf986172009-01-02 07:01:27 +00003474 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3475 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003476
Chris Lattnerdf986172009-01-02 07:01:27 +00003477 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3478 return false;
3479}
3480
3481/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003482/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003483int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003484 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003485 Value *Op0, *Op1;
3486 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003487
Chris Lattnerdf986172009-01-02 07:01:27 +00003488 if (ParseType(Ty) ||
3489 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3490 ParseValue(Ty, Op0, PFS) ||
3491 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003492 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003493 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3494 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003495
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003496 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003497 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3498 while (1) {
3499 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003500
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003501 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003502 break;
3503
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003504 if (Lex.getKind() == lltok::MetadataVar) {
3505 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003506 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003507 }
Devang Patela43d46f2009-10-16 18:45:49 +00003508
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003509 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003510 ParseValue(Ty, Op0, PFS) ||
3511 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003512 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003513 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3514 return true;
3515 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003516
Chris Lattnerdf986172009-01-02 07:01:27 +00003517 if (!Ty->isFirstClassType())
3518 return Error(TypeLoc, "phi node must have first class type");
3519
Jay Foad3ecfc862011-03-30 11:28:46 +00003520 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003521 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3522 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3523 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003524 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003525}
3526
3527/// ParseCall
3528/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3529/// ParameterList OptionalAttrs
3530bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3531 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003532 unsigned RetAttrs, FnAttrs;
3533 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003534 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003535 LocTy RetTypeLoc;
3536 ValID CalleeID;
3537 SmallVector<ParamInfo, 16> ArgList;
3538 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003539
Chris Lattnerdf986172009-01-02 07:01:27 +00003540 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3541 ParseOptionalCallingConv(CC) ||
3542 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003543 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003544 ParseValID(CalleeID) ||
3545 ParseParameterList(ArgList, PFS) ||
3546 ParseOptionalAttrs(FnAttrs, 2))
3547 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003548
Chris Lattnerdf986172009-01-02 07:01:27 +00003549 // If RetType is a non-function pointer type, then this is the short syntax
3550 // for the call, which means that RetType is just the return type. Infer the
3551 // rest of the function argument types from the arguments that are present.
3552 const PointerType *PFTy = 0;
3553 const FunctionType *Ty = 0;
3554 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3555 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3556 // Pull out the types of all of the arguments...
3557 std::vector<const Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003558 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3559 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003560
Chris Lattnerdf986172009-01-02 07:01:27 +00003561 if (!FunctionType::isValidReturnType(RetType))
3562 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003563
Owen Andersondebcb012009-07-29 22:17:13 +00003564 Ty = FunctionType::get(RetType, ParamTypes, false);
3565 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003566 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003567
Chris Lattnerdf986172009-01-02 07:01:27 +00003568 // Look up the callee.
3569 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003570 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003571
Chris Lattnerdf986172009-01-02 07:01:27 +00003572 // Set up the Attributes for the function.
3573 SmallVector<AttributeWithIndex, 8> Attrs;
3574 if (RetAttrs != Attribute::None)
3575 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003576
Chris Lattnerdf986172009-01-02 07:01:27 +00003577 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003578
Chris Lattnerdf986172009-01-02 07:01:27 +00003579 // Loop through FunctionType's arguments and ensure they are specified
3580 // correctly. Also, gather any parameter attributes.
3581 FunctionType::param_iterator I = Ty->param_begin();
3582 FunctionType::param_iterator E = Ty->param_end();
3583 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3584 const Type *ExpectedTy = 0;
3585 if (I != E) {
3586 ExpectedTy = *I++;
3587 } else if (!Ty->isVarArg()) {
3588 return Error(ArgList[i].Loc, "too many arguments specified");
3589 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003590
Chris Lattnerdf986172009-01-02 07:01:27 +00003591 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3592 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003593 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003594 Args.push_back(ArgList[i].V);
3595 if (ArgList[i].Attrs != Attribute::None)
3596 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3597 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003598
Chris Lattnerdf986172009-01-02 07:01:27 +00003599 if (I != E)
3600 return Error(CallLoc, "not enough parameters specified for call");
3601
3602 if (FnAttrs != Attribute::None)
3603 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3604
3605 // Finish off the Attributes and check them
3606 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003607
Chris Lattnerdf986172009-01-02 07:01:27 +00003608 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3609 CI->setTailCall(isTail);
3610 CI->setCallingConv(CC);
3611 CI->setAttributes(PAL);
3612 Inst = CI;
3613 return false;
3614}
3615
3616//===----------------------------------------------------------------------===//
3617// Memory Instructions.
3618//===----------------------------------------------------------------------===//
3619
3620/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003621/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003622int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003623 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003624 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003625 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003626 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003627 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003628
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003629 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003630 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003631 if (Lex.getKind() == lltok::kw_align) {
3632 if (ParseOptionalAlignment(Alignment)) return true;
3633 } else if (Lex.getKind() == lltok::MetadataVar) {
3634 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003635 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003636 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3637 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3638 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003639 }
3640 }
3641
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003642 if (Size && !Size->getType()->isIntegerTy())
3643 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003644
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003645 Inst = new AllocaInst(Ty, Size, Alignment);
3646 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003647}
3648
3649/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003650/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003651int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3652 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003653 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003654 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003655 bool AteExtraComma = false;
3656 if (ParseTypeAndValue(Val, Loc, PFS) ||
3657 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3658 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003659
Duncan Sands1df98592010-02-16 11:11:14 +00003660 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003661 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3662 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003663
Chris Lattnerdf986172009-01-02 07:01:27 +00003664 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003665 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003666}
3667
3668/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003669/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003670int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3671 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003672 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003673 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003674 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003675 if (ParseTypeAndValue(Val, Loc, PFS) ||
3676 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003677 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3678 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003679 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003680
Duncan Sands1df98592010-02-16 11:11:14 +00003681 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003682 return Error(PtrLoc, "store operand must be a pointer");
3683 if (!Val->getType()->isFirstClassType())
3684 return Error(Loc, "store operand must be a first class value");
3685 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3686 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003687
Chris Lattnerdf986172009-01-02 07:01:27 +00003688 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003689 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003690}
3691
Chris Lattnerdf986172009-01-02 07:01:27 +00003692/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003693/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003694int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003695 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003696
Dan Gohmandcb40a32009-07-29 15:58:36 +00003697 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003698
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003699 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003700
Duncan Sands1df98592010-02-16 11:11:14 +00003701 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003702 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003703
Chris Lattnerdf986172009-01-02 07:01:27 +00003704 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003705 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003706 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003707 if (Lex.getKind() == lltok::MetadataVar) {
3708 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003709 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003710 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003711 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003712 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003713 return Error(EltLoc, "getelementptr index must be an integer");
3714 Indices.push_back(Val);
3715 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003716
Chris Lattnerdf986172009-01-02 07:01:27 +00003717 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3718 Indices.begin(), Indices.end()))
3719 return Error(Loc, "invalid getelementptr indices");
3720 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003721 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003722 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003723 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003724}
3725
3726/// ParseExtractValue
3727/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003728int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003729 Value *Val; LocTy Loc;
3730 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003731 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003732 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003733 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003734 return true;
3735
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003736 if (!Val->getType()->isAggregateType())
3737 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003738
3739 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3740 Indices.end()))
3741 return Error(Loc, "invalid indices for extractvalue");
3742 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003743 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003744}
3745
3746/// ParseInsertValue
3747/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003748int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003749 Value *Val0, *Val1; LocTy Loc0, Loc1;
3750 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003751 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003752 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3753 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3754 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003755 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003756 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003757
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003758 if (!Val0->getType()->isAggregateType())
3759 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003760
Chris Lattnerdf986172009-01-02 07:01:27 +00003761 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3762 Indices.end()))
3763 return Error(Loc0, "invalid indices for insertvalue");
3764 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003765 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003766}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003767
3768//===----------------------------------------------------------------------===//
3769// Embedded metadata.
3770//===----------------------------------------------------------------------===//
3771
3772/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003773/// ::= Element (',' Element)*
3774/// Element
3775/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003776bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003777 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003778 // Check for an empty list.
3779 if (Lex.getKind() == lltok::rbrace)
3780 return false;
3781
Nick Lewycky21cc4462009-04-04 07:22:01 +00003782 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003783 // Null is a special case since it is typeless.
3784 if (EatIfPresent(lltok::kw_null)) {
3785 Elts.push_back(0);
3786 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003787 }
Chris Lattnera7352392009-12-30 04:42:57 +00003788
3789 Value *V = 0;
3790 PATypeHolder Ty(Type::getVoidTy(Context));
3791 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003792 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003793 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003794 return true;
3795
Nick Lewyckycb337992009-05-10 20:57:05 +00003796 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003797 } while (EatIfPresent(lltok::comma));
3798
3799 return false;
3800}