blob: 67521814b0c6aa12dddc9f38d76ea82034221b1e [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"
25#include "llvm/ADT/StringExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000027#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
Chris Lattner3ed88ef2009-01-02 08:05:26 +000030/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000031bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000032 // Prime the lexer.
33 Lex.Lex();
34
Chris Lattnerad7d1e22009-01-04 20:44:11 +000035 return ParseTopLevelEntities() ||
36 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000037}
38
39/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
40/// module.
41bool LLParser::ValidateEndOfModule() {
Chris Lattner449c3102010-04-01 05:14:45 +000042 // Handle any instruction metadata forward references.
43 if (!ForwardRefInstMetadata.empty()) {
44 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
45 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
46 I != E; ++I) {
47 Instruction *Inst = I->first;
48 const std::vector<MDRef> &MDList = I->second;
49
50 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
51 unsigned SlotNo = MDList[i].MDSlot;
52
53 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
54 return Error(MDList[i].Loc, "use of undefined metadata '!" +
55 utostr(SlotNo) + "'");
56 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
57 }
58 }
59 ForwardRefInstMetadata.clear();
60 }
61
62
Victor Hernandez68afa542009-10-21 19:11:40 +000063 // Update auto-upgraded malloc calls to "malloc".
Chris Lattnercf4d2f12009-10-18 05:09:15 +000064 // FIXME: Remove in LLVM 3.0.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000065 if (MallocF) {
66 MallocF->setName("malloc");
67 // If setName() does not set the name to "malloc", then there is already a
68 // declaration of "malloc". In that case, iterate over all calls to MallocF
69 // and get them to call the declared "malloc" instead.
70 if (MallocF->getName() != "malloc") {
Chris Lattner09d9ef42009-10-28 03:39:23 +000071 Constant *RealMallocF = M->getFunction("malloc");
Victor Hernandez68afa542009-10-21 19:11:40 +000072 if (RealMallocF->getType() != MallocF->getType())
73 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
74 MallocF->replaceAllUsesWith(RealMallocF);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000075 MallocF->eraseFromParent();
76 MallocF = NULL;
77 }
78 }
Chris Lattner09d9ef42009-10-28 03:39:23 +000079
80
81 // If there are entries in ForwardRefBlockAddresses at this point, they are
82 // references after the function was defined. Resolve those now.
83 while (!ForwardRefBlockAddresses.empty()) {
84 // Okay, we are referencing an already-parsed function, resolve them now.
85 Function *TheFn = 0;
86 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
87 if (Fn.Kind == ValID::t_GlobalName)
88 TheFn = M->getFunction(Fn.StrVal);
89 else if (Fn.UIntVal < NumberedVals.size())
90 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
91
92 if (TheFn == 0)
93 return Error(Fn.Loc, "unknown function referenced by blockaddress");
94
95 // Resolve all these references.
96 if (ResolveForwardRefBlockAddresses(TheFn,
97 ForwardRefBlockAddresses.begin()->second,
98 0))
99 return true;
100
101 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
102 }
103
104
Chris Lattnerdf986172009-01-02 07:01:27 +0000105 if (!ForwardRefTypes.empty())
106 return Error(ForwardRefTypes.begin()->second.second,
107 "use of undefined type named '" +
108 ForwardRefTypes.begin()->first + "'");
109 if (!ForwardRefTypeIDs.empty())
110 return Error(ForwardRefTypeIDs.begin()->second.second,
111 "use of undefined type '%" +
112 utostr(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000113
Chris Lattnerdf986172009-01-02 07:01:27 +0000114 if (!ForwardRefVals.empty())
115 return Error(ForwardRefVals.begin()->second.second,
116 "use of undefined value '@" + ForwardRefVals.begin()->first +
117 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000118
Chris Lattnerdf986172009-01-02 07:01:27 +0000119 if (!ForwardRefValIDs.empty())
120 return Error(ForwardRefValIDs.begin()->second.second,
121 "use of undefined value '@" +
122 utostr(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000123
Devang Patel1c7eea62009-07-08 19:23:54 +0000124 if (!ForwardRefMDNodes.empty())
125 return Error(ForwardRefMDNodes.begin()->second.second,
126 "use of undefined metadata '!" +
127 utostr(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000128
Devang Patel1c7eea62009-07-08 19:23:54 +0000129
Chris Lattnerdf986172009-01-02 07:01:27 +0000130 // Look for intrinsic functions and CallInst that need to be upgraded
131 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
132 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000133
Devang Patele4b27562009-08-28 23:24:31 +0000134 // Check debug info intrinsics.
135 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000136 return false;
137}
138
Chris Lattner09d9ef42009-10-28 03:39:23 +0000139bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
140 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
141 PerFunctionState *PFS) {
142 // Loop over all the references, resolving them.
143 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
144 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000145 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000146 if (Refs[i].first.Kind == ValID::t_LocalName)
147 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000148 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000149 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
150 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
151 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000152 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000153 } else {
154 Res = dyn_cast_or_null<BasicBlock>(
155 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
156 }
157
Chris Lattnercdfc9402009-11-01 01:27:45 +0000158 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000159 return Error(Refs[i].first.Loc,
160 "referenced value is not a basic block");
161
162 // Get the BlockAddress for this and update references to use it.
163 BlockAddress *BA = BlockAddress::get(TheFn, Res);
164 Refs[i].second->replaceAllUsesWith(BA);
165 Refs[i].second->eraseFromParent();
166 }
167 return false;
168}
169
170
Chris Lattnerdf986172009-01-02 07:01:27 +0000171//===----------------------------------------------------------------------===//
172// Top-Level Entities
173//===----------------------------------------------------------------------===//
174
175bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000176 while (1) {
177 switch (Lex.getKind()) {
178 default: return TokError("expected top-level entity");
179 case lltok::Eof: return false;
180 //case lltok::kw_define:
181 case lltok::kw_declare: if (ParseDeclare()) return true; break;
182 case lltok::kw_define: if (ParseDefine()) return true; break;
183 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
184 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
185 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
186 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000187 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000188 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
189 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000190 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000191 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000192 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000193 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000194
195 // The Global variable production with no name can have many different
196 // optional leading prefixes, the production is:
197 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
198 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000199 case lltok::kw_private: // OptionalLinkage
200 case lltok::kw_linker_private: // OptionalLinkage
201 case lltok::kw_linker_private_weak: // OptionalLinkage
202 case lltok::kw_internal: // OptionalLinkage
203 case lltok::kw_weak: // OptionalLinkage
204 case lltok::kw_weak_odr: // OptionalLinkage
205 case lltok::kw_linkonce: // OptionalLinkage
206 case lltok::kw_linkonce_odr: // OptionalLinkage
207 case lltok::kw_appending: // OptionalLinkage
208 case lltok::kw_dllexport: // OptionalLinkage
209 case lltok::kw_common: // OptionalLinkage
210 case lltok::kw_dllimport: // OptionalLinkage
211 case lltok::kw_extern_weak: // OptionalLinkage
212 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000213 unsigned Linkage, Visibility;
214 if (ParseOptionalLinkage(Linkage) ||
215 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000216 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000217 return true;
218 break;
219 }
220 case lltok::kw_default: // OptionalVisibility
221 case lltok::kw_hidden: // OptionalVisibility
222 case lltok::kw_protected: { // OptionalVisibility
223 unsigned Visibility;
224 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000225 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000226 return true;
227 break;
228 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000229
Chris Lattnerdf986172009-01-02 07:01:27 +0000230 case lltok::kw_thread_local: // OptionalThreadLocal
231 case lltok::kw_addrspace: // OptionalAddrSpace
232 case lltok::kw_constant: // GlobalType
233 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000234 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000235 break;
236 }
237 }
238}
239
240
241/// toplevelentity
242/// ::= 'module' 'asm' STRINGCONSTANT
243bool LLParser::ParseModuleAsm() {
244 assert(Lex.getKind() == lltok::kw_module);
245 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000246
247 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000248 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
249 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000250
Chris Lattnerdf986172009-01-02 07:01:27 +0000251 const std::string &AsmSoFar = M->getModuleInlineAsm();
252 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000253 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000254 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000255 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000256 return false;
257}
258
259/// toplevelentity
260/// ::= 'target' 'triple' '=' STRINGCONSTANT
261/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
262bool LLParser::ParseTargetDefinition() {
263 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000264 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000265 switch (Lex.Lex()) {
266 default: return TokError("unknown target property");
267 case lltok::kw_triple:
268 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000269 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
270 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000271 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000272 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000273 return false;
274 case lltok::kw_datalayout:
275 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000276 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
277 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000278 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000279 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000280 return false;
281 }
282}
283
284/// toplevelentity
285/// ::= 'deplibs' '=' '[' ']'
286/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
287bool LLParser::ParseDepLibs() {
288 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000289 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000290 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
291 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
292 return true;
293
294 if (EatIfPresent(lltok::rsquare))
295 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000296
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000297 std::string Str;
298 if (ParseStringConstant(Str)) return true;
299 M->addLibrary(Str);
300
301 while (EatIfPresent(lltok::comma)) {
302 if (ParseStringConstant(Str)) return true;
303 M->addLibrary(Str);
304 }
305
306 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000307}
308
Dan Gohman3845e502009-08-12 23:32:33 +0000309/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000310/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000311/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000312bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000313 unsigned TypeID = NumberedTypes.size();
314
315 // Handle the LocalVarID form.
316 if (Lex.getKind() == lltok::LocalVarID) {
317 if (Lex.getUIntVal() != TypeID)
318 return Error(Lex.getLoc(), "type expected to be numbered '%" +
319 utostr(TypeID) + "'");
320 Lex.Lex(); // eat LocalVarID;
321
322 if (ParseToken(lltok::equal, "expected '=' after name"))
323 return true;
324 }
325
Chris Lattnerdf986172009-01-02 07:01:27 +0000326 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerf7240de2010-04-10 18:01:25 +0000327 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000328
Owen Anderson1d0be152009-08-13 21:58:54 +0000329 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000330 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000331
Chris Lattnerdf986172009-01-02 07:01:27 +0000332 // See if this type was previously referenced.
333 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
334 FI = ForwardRefTypeIDs.find(TypeID);
335 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000336 if (FI->second.first.get() == Ty)
337 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000338
Chris Lattnerdf986172009-01-02 07:01:27 +0000339 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
340 Ty = FI->second.first.get();
341 ForwardRefTypeIDs.erase(FI);
342 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000343
Chris Lattnerdf986172009-01-02 07:01:27 +0000344 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000345
Chris Lattnerdf986172009-01-02 07:01:27 +0000346 return false;
347}
348
349/// toplevelentity
350/// ::= LocalVar '=' 'type' type
351bool LLParser::ParseNamedType() {
352 std::string Name = Lex.getStrVal();
353 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000354 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000355
Owen Anderson1d0be152009-08-13 21:58:54 +0000356 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000357
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000358 if (ParseToken(lltok::equal, "expected '=' after name") ||
359 ParseToken(lltok::kw_type, "expected 'type' after name") ||
360 ParseType(Ty))
361 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Chris Lattnerdf986172009-01-02 07:01:27 +0000363 // Set the type name, checking for conflicts as we do so.
364 bool AlreadyExists = M->addTypeName(Name, Ty);
365 if (!AlreadyExists) return false;
366
367 // See if this type is a forward reference. We need to eagerly resolve
368 // types to allow recursive type redefinitions below.
369 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
370 FI = ForwardRefTypes.find(Name);
371 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000372 if (FI->second.first.get() == Ty)
373 return Error(NameLoc, "self referential type is invalid");
374
Chris Lattnerdf986172009-01-02 07:01:27 +0000375 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
376 Ty = FI->second.first.get();
377 ForwardRefTypes.erase(FI);
378 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000379
Chris Lattnerdf986172009-01-02 07:01:27 +0000380 // Inserting a name that is already defined, get the existing name.
381 const Type *Existing = M->getTypeByName(Name);
382 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000383
Chris Lattnerdf986172009-01-02 07:01:27 +0000384 // Otherwise, this is an attempt to redefine a type. That's okay if
385 // the redefinition is identical to the original.
386 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
387 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000388
Chris Lattnerdf986172009-01-02 07:01:27 +0000389 // Any other kind of (non-equivalent) redefinition is an error.
390 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
391 Ty->getDescription() + "'");
392}
393
394
395/// toplevelentity
396/// ::= 'declare' FunctionHeader
397bool LLParser::ParseDeclare() {
398 assert(Lex.getKind() == lltok::kw_declare);
399 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000400
Chris Lattnerdf986172009-01-02 07:01:27 +0000401 Function *F;
402 return ParseFunctionHeader(F, false);
403}
404
405/// toplevelentity
406/// ::= 'define' FunctionHeader '{' ...
407bool LLParser::ParseDefine() {
408 assert(Lex.getKind() == lltok::kw_define);
409 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000410
Chris Lattnerdf986172009-01-02 07:01:27 +0000411 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000412 return ParseFunctionHeader(F, true) ||
413 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000414}
415
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000416/// ParseGlobalType
417/// ::= 'constant'
418/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000419bool LLParser::ParseGlobalType(bool &IsConstant) {
420 if (Lex.getKind() == lltok::kw_constant)
421 IsConstant = true;
422 else if (Lex.getKind() == lltok::kw_global)
423 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000424 else {
425 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000426 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000427 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000428 Lex.Lex();
429 return false;
430}
431
Dan Gohman3845e502009-08-12 23:32:33 +0000432/// ParseUnnamedGlobal:
433/// OptionalVisibility ALIAS ...
434/// OptionalLinkage OptionalVisibility ... -> global variable
435/// GlobalID '=' OptionalVisibility ALIAS ...
436/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
437bool LLParser::ParseUnnamedGlobal() {
438 unsigned VarID = NumberedVals.size();
439 std::string Name;
440 LocTy NameLoc = Lex.getLoc();
441
442 // Handle the GlobalID form.
443 if (Lex.getKind() == lltok::GlobalID) {
444 if (Lex.getUIntVal() != VarID)
445 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
446 utostr(VarID) + "'");
447 Lex.Lex(); // eat GlobalID;
448
449 if (ParseToken(lltok::equal, "expected '=' after name"))
450 return true;
451 }
452
453 bool HasLinkage;
454 unsigned Linkage, Visibility;
455 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
456 ParseOptionalVisibility(Visibility))
457 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000458
Dan Gohman3845e502009-08-12 23:32:33 +0000459 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
460 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
461 return ParseAlias(Name, NameLoc, Visibility);
462}
463
Chris Lattnerdf986172009-01-02 07:01:27 +0000464/// ParseNamedGlobal:
465/// GlobalVar '=' OptionalVisibility ALIAS ...
466/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
467bool LLParser::ParseNamedGlobal() {
468 assert(Lex.getKind() == lltok::GlobalVar);
469 LocTy NameLoc = Lex.getLoc();
470 std::string Name = Lex.getStrVal();
471 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000472
Chris Lattnerdf986172009-01-02 07:01:27 +0000473 bool HasLinkage;
474 unsigned Linkage, Visibility;
475 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
476 ParseOptionalLinkage(Linkage, HasLinkage) ||
477 ParseOptionalVisibility(Visibility))
478 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000479
Chris Lattnerdf986172009-01-02 07:01:27 +0000480 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
481 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
482 return ParseAlias(Name, NameLoc, Visibility);
483}
484
Devang Patel256be962009-07-20 19:00:08 +0000485// MDString:
486// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000487bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000488 std::string Str;
489 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000490 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000491 return false;
492}
493
494// MDNode:
495// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000496//
497/// This version of ParseMDNodeID returns the slot number and null in the case
498/// of a forward reference.
499bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
500 // !{ ..., !42, ... }
501 if (ParseUInt32(SlotNo)) return true;
502
503 // Check existing MDNode.
504 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
505 Result = NumberedMetadata[SlotNo];
506 else
507 Result = 0;
508 return false;
509}
510
Chris Lattner4a72efc2009-12-30 04:15:23 +0000511bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000512 // !{ ..., !42, ... }
513 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000514 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000515
Chris Lattner449c3102010-04-01 05:14:45 +0000516 // If not a forward reference, just return it now.
517 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000518
Chris Lattner449c3102010-04-01 05:14:45 +0000519 // Otherwise, create MDNode forward reference.
Chris Lattner42991ee2009-12-29 22:01:50 +0000520
521 // FIXME: This is not unique enough!
Devang Patel256be962009-07-20 19:00:08 +0000522 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Benjamin Kramerc17300f2009-12-29 22:17:06 +0000523 Value *V = MDString::get(Context, FwdRefName);
Chris Lattner42991ee2009-12-29 22:01:50 +0000524 MDNode *FwdNode = MDNode::get(Context, &V, 1);
Devang Patel256be962009-07-20 19:00:08 +0000525 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000526
527 if (NumberedMetadata.size() <= MID)
528 NumberedMetadata.resize(MID+1);
529 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000530 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000531 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000532}
Devang Patel256be962009-07-20 19:00:08 +0000533
Chris Lattner84d03b12009-12-29 22:35:39 +0000534/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000535/// !foo = !{ !1, !2 }
536bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000537 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000538 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000539 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000540
Chris Lattner84d03b12009-12-29 22:35:39 +0000541 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000542 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000543 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000544 return true;
545
Devang Patel3e30c2a2010-01-05 20:41:31 +0000546 SmallVector<MDNode *, 8> Elts;
Devang Pateleff2ab62009-07-29 00:34:02 +0000547 do {
Devang Patel69d02e02010-01-05 21:47:32 +0000548 // Null is a special case since it is typeless.
549 if (EatIfPresent(lltok::kw_null)) {
550 Elts.push_back(0);
551 continue;
552 }
553
Chris Lattnere434d272009-12-30 04:56:59 +0000554 if (ParseToken(lltok::exclaim, "Expected '!' here"))
Chris Lattner42991ee2009-12-29 22:01:50 +0000555 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000556
Chris Lattner442ffa12009-12-29 21:53:55 +0000557 MDNode *N = 0;
Chris Lattner4a72efc2009-12-30 04:15:23 +0000558 if (ParseMDNodeID(N)) return true;
Devang Pateleff2ab62009-07-29 00:34:02 +0000559 Elts.push_back(N);
560 } while (EatIfPresent(lltok::comma));
561
562 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
563 return true;
564
Owen Anderson1d0be152009-08-13 21:58:54 +0000565 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000566 return false;
567}
568
Devang Patel923078c2009-07-01 19:21:12 +0000569/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000570/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000571bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000572 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000573 Lex.Lex();
574 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000575
576 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000577 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000578 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000579 if (ParseUInt32(MetadataID) ||
580 ParseToken(lltok::equal, "expected '=' here") ||
581 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000582 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000583 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000584 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000585 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000586 return true;
587
Owen Anderson647e3012009-07-31 21:35:40 +0000588 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000589
590 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000591 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000592 FI = ForwardRefMDNodes.find(MetadataID);
593 if (FI != ForwardRefMDNodes.end()) {
Chris Lattnere80250e2009-12-29 21:43:58 +0000594 FI->second.first->replaceAllUsesWith(Init);
Devang Patel1c7eea62009-07-08 19:23:54 +0000595 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000596
597 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
598 } else {
599 if (MetadataID >= NumberedMetadata.size())
600 NumberedMetadata.resize(MetadataID+1);
601
602 if (NumberedMetadata[MetadataID] != 0)
603 return TokError("Metadata id is already used");
604 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000605 }
606
Devang Patel923078c2009-07-01 19:21:12 +0000607 return false;
608}
609
Chris Lattnerdf986172009-01-02 07:01:27 +0000610/// ParseAlias:
611/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
612/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000613/// ::= TypeAndValue
614/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000615/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000616///
617/// Everything through visibility has already been parsed.
618///
619bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
620 unsigned Visibility) {
621 assert(Lex.getKind() == lltok::kw_alias);
622 Lex.Lex();
623 unsigned Linkage;
624 LocTy LinkageLoc = Lex.getLoc();
625 if (ParseOptionalLinkage(Linkage))
626 return true;
627
628 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000629 Linkage != GlobalValue::WeakAnyLinkage &&
630 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000631 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000632 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000633 Linkage != GlobalValue::LinkerPrivateLinkage &&
634 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000635 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000636
Chris Lattnerdf986172009-01-02 07:01:27 +0000637 Constant *Aliasee;
638 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000639 if (Lex.getKind() != lltok::kw_bitcast &&
640 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000641 if (ParseGlobalTypeAndValue(Aliasee)) return true;
642 } else {
643 // The bitcast dest type is not present, it is implied by the dest type.
644 ValID ID;
645 if (ParseValID(ID)) return true;
646 if (ID.Kind != ValID::t_Constant)
647 return Error(AliaseeLoc, "invalid aliasee");
648 Aliasee = ID.ConstantVal;
649 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000650
Duncan Sands1df98592010-02-16 11:11:14 +0000651 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000652 return Error(AliaseeLoc, "alias must have pointer type");
653
654 // Okay, create the alias but do not insert it into the module yet.
655 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
656 (GlobalValue::LinkageTypes)Linkage, Name,
657 Aliasee);
658 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000659
Chris Lattnerdf986172009-01-02 07:01:27 +0000660 // See if this value already exists in the symbol table. If so, it is either
661 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000662 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000663 // See if this was a redefinition. If so, there is no entry in
664 // ForwardRefVals.
665 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
666 I = ForwardRefVals.find(Name);
667 if (I == ForwardRefVals.end())
668 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
669
670 // Otherwise, this was a definition of forward ref. Verify that types
671 // agree.
672 if (Val->getType() != GA->getType())
673 return Error(NameLoc,
674 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000675
Chris Lattnerdf986172009-01-02 07:01:27 +0000676 // If they agree, just RAUW the old value with the alias and remove the
677 // forward ref info.
678 Val->replaceAllUsesWith(GA);
679 Val->eraseFromParent();
680 ForwardRefVals.erase(I);
681 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000682
Chris Lattnerdf986172009-01-02 07:01:27 +0000683 // Insert into the module, we know its name won't collide now.
684 M->getAliasList().push_back(GA);
685 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000686
Chris Lattnerdf986172009-01-02 07:01:27 +0000687 return false;
688}
689
690/// ParseGlobal
691/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
692/// OptionalAddrSpace GlobalType Type Const
693/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
694/// OptionalAddrSpace GlobalType Type Const
695///
696/// Everything through visibility has been parsed already.
697///
698bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
699 unsigned Linkage, bool HasLinkage,
700 unsigned Visibility) {
701 unsigned AddrSpace;
702 bool ThreadLocal, IsConstant;
703 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000704
Owen Anderson1d0be152009-08-13 21:58:54 +0000705 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000706 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
707 ParseOptionalAddrSpace(AddrSpace) ||
708 ParseGlobalType(IsConstant) ||
709 ParseType(Ty, TyLoc))
710 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000711
Chris Lattnerdf986172009-01-02 07:01:27 +0000712 // If the linkage is specified and is external, then no initializer is
713 // present.
714 Constant *Init = 0;
715 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000716 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000717 Linkage != GlobalValue::ExternalLinkage)) {
718 if (ParseGlobalValue(Ty, Init))
719 return true;
720 }
721
Duncan Sands1df98592010-02-16 11:11:14 +0000722 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000723 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000724
Chris Lattnerdf986172009-01-02 07:01:27 +0000725 GlobalVariable *GV = 0;
726
727 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000728 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000729 if (GlobalValue *GVal = M->getNamedValue(Name)) {
730 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
731 return Error(NameLoc, "redefinition of global '@" + Name + "'");
732 GV = cast<GlobalVariable>(GVal);
733 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000734 } else {
735 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
736 I = ForwardRefValIDs.find(NumberedVals.size());
737 if (I != ForwardRefValIDs.end()) {
738 GV = cast<GlobalVariable>(I->second.first);
739 ForwardRefValIDs.erase(I);
740 }
741 }
742
743 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000744 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000745 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000746 } else {
747 if (GV->getType()->getElementType() != Ty)
748 return Error(TyLoc,
749 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000750
Chris Lattnerdf986172009-01-02 07:01:27 +0000751 // Move the forward-reference to the correct spot in the module.
752 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
753 }
754
755 if (Name.empty())
756 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000757
Chris Lattnerdf986172009-01-02 07:01:27 +0000758 // Set the parsed properties on the global.
759 if (Init)
760 GV->setInitializer(Init);
761 GV->setConstant(IsConstant);
762 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
763 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
764 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000765
Chris Lattnerdf986172009-01-02 07:01:27 +0000766 // Parse attributes on the global.
767 while (Lex.getKind() == lltok::comma) {
768 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000769
Chris Lattnerdf986172009-01-02 07:01:27 +0000770 if (Lex.getKind() == lltok::kw_section) {
771 Lex.Lex();
772 GV->setSection(Lex.getStrVal());
773 if (ParseToken(lltok::StringConstant, "expected global section string"))
774 return true;
775 } else if (Lex.getKind() == lltok::kw_align) {
776 unsigned Alignment;
777 if (ParseOptionalAlignment(Alignment)) return true;
778 GV->setAlignment(Alignment);
779 } else {
780 TokError("unknown global variable property!");
781 }
782 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000783
Chris Lattnerdf986172009-01-02 07:01:27 +0000784 return false;
785}
786
787
788//===----------------------------------------------------------------------===//
789// GlobalValue Reference/Resolution Routines.
790//===----------------------------------------------------------------------===//
791
792/// GetGlobalVal - Get a value with the specified name or ID, creating a
793/// forward reference record if needed. This can return null if the value
794/// exists but does not have the right type.
795GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
796 LocTy Loc) {
797 const PointerType *PTy = dyn_cast<PointerType>(Ty);
798 if (PTy == 0) {
799 Error(Loc, "global variable reference must have pointer type");
800 return 0;
801 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000802
Chris Lattnerdf986172009-01-02 07:01:27 +0000803 // Look this name up in the normal function symbol table.
804 GlobalValue *Val =
805 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000806
Chris Lattnerdf986172009-01-02 07:01:27 +0000807 // If this is a forward reference for the value, see if we already created a
808 // forward ref record.
809 if (Val == 0) {
810 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
811 I = ForwardRefVals.find(Name);
812 if (I != ForwardRefVals.end())
813 Val = I->second.first;
814 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000815
Chris Lattnerdf986172009-01-02 07:01:27 +0000816 // If we have the value in the symbol table or fwd-ref table, return it.
817 if (Val) {
818 if (Val->getType() == Ty) return Val;
819 Error(Loc, "'@" + Name + "' defined with type '" +
820 Val->getType()->getDescription() + "'");
821 return 0;
822 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000823
Chris Lattnerdf986172009-01-02 07:01:27 +0000824 // Otherwise, create a new forward reference for this value and remember it.
825 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000826 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
827 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000828 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000829 Error(Loc, "function may not return opaque type");
830 return 0;
831 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000832
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000833 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000834 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000835 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
836 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000837 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000838
Chris Lattnerdf986172009-01-02 07:01:27 +0000839 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
840 return FwdVal;
841}
842
843GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
844 const PointerType *PTy = dyn_cast<PointerType>(Ty);
845 if (PTy == 0) {
846 Error(Loc, "global variable reference must have pointer type");
847 return 0;
848 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000849
Chris Lattnerdf986172009-01-02 07:01:27 +0000850 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000851
Chris Lattnerdf986172009-01-02 07:01:27 +0000852 // If this is a forward reference for the value, see if we already created a
853 // forward ref record.
854 if (Val == 0) {
855 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
856 I = ForwardRefValIDs.find(ID);
857 if (I != ForwardRefValIDs.end())
858 Val = I->second.first;
859 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000860
Chris Lattnerdf986172009-01-02 07:01:27 +0000861 // If we have the value in the symbol table or fwd-ref table, return it.
862 if (Val) {
863 if (Val->getType() == Ty) return Val;
864 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
865 Val->getType()->getDescription() + "'");
866 return 0;
867 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000868
Chris Lattnerdf986172009-01-02 07:01:27 +0000869 // Otherwise, create a new forward reference for this value and remember it.
870 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000871 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
872 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000873 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000874 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000875 return 0;
876 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000877 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000878 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000879 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
880 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000881 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000882
Chris Lattnerdf986172009-01-02 07:01:27 +0000883 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
884 return FwdVal;
885}
886
887
888//===----------------------------------------------------------------------===//
889// Helper Routines.
890//===----------------------------------------------------------------------===//
891
892/// ParseToken - If the current token has the specified kind, eat it and return
893/// success. Otherwise, emit the specified error and return failure.
894bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
895 if (Lex.getKind() != T)
896 return TokError(ErrMsg);
897 Lex.Lex();
898 return false;
899}
900
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000901/// ParseStringConstant
902/// ::= StringConstant
903bool LLParser::ParseStringConstant(std::string &Result) {
904 if (Lex.getKind() != lltok::StringConstant)
905 return TokError("expected string constant");
906 Result = Lex.getStrVal();
907 Lex.Lex();
908 return false;
909}
910
911/// ParseUInt32
912/// ::= uint32
913bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000914 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
915 return TokError("expected integer");
916 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
917 if (Val64 != unsigned(Val64))
918 return TokError("expected 32-bit integer (too large)");
919 Val = Val64;
920 Lex.Lex();
921 return false;
922}
923
924
925/// ParseOptionalAddrSpace
926/// := /*empty*/
927/// := 'addrspace' '(' uint32 ')'
928bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
929 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000930 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000931 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000932 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000933 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000934 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000935}
Chris Lattnerdf986172009-01-02 07:01:27 +0000936
937/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
938/// indicates what kind of attribute list this is: 0: function arg, 1: result,
939/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000940/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000941bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
942 Attrs = Attribute::None;
943 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000944
Chris Lattnerdf986172009-01-02 07:01:27 +0000945 while (1) {
946 switch (Lex.getKind()) {
947 case lltok::kw_sext:
948 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000949 // Treat these as signext/zeroext if they occur in the argument list after
950 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
951 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
952 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000953 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000954 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000955 if (Lex.getKind() == lltok::kw_sext)
956 Attrs |= Attribute::SExt;
957 else
958 Attrs |= Attribute::ZExt;
959 break;
960 }
961 // FALL THROUGH.
962 default: // End of attributes.
963 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
964 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000965
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000966 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000967 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000968
Chris Lattnerdf986172009-01-02 07:01:27 +0000969 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000970 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
971 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
972 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
973 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
974 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
975 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
976 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
977 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000978
Devang Patel578efa92009-06-05 21:57:13 +0000979 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
980 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
981 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
982 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
983 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000984 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000985 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
986 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
987 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
988 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
989 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
990 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000991 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000992
Charles Davis1e063d12010-02-12 00:31:15 +0000993 case lltok::kw_alignstack: {
994 unsigned Alignment;
995 if (ParseOptionalStackAlignment(Alignment))
996 return true;
997 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
998 continue;
999 }
1000
Chris Lattnerdf986172009-01-02 07:01:27 +00001001 case lltok::kw_align: {
1002 unsigned Alignment;
1003 if (ParseOptionalAlignment(Alignment))
1004 return true;
1005 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1006 continue;
1007 }
Charles Davis1e063d12010-02-12 00:31:15 +00001008
Chris Lattnerdf986172009-01-02 07:01:27 +00001009 }
1010 Lex.Lex();
1011 }
1012}
1013
1014/// ParseOptionalLinkage
1015/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001016/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001017/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001018/// ::= 'linker_private_weak'
Chris Lattnerdf986172009-01-02 07:01:27 +00001019/// ::= 'internal'
1020/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001021/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001022/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001023/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +00001024/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001025/// ::= 'appending'
1026/// ::= 'dllexport'
1027/// ::= 'common'
1028/// ::= 'dllimport'
1029/// ::= 'extern_weak'
1030/// ::= 'external'
1031bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1032 HasLinkage = false;
1033 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001034 default: Res=GlobalValue::ExternalLinkage; return false;
1035 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1036 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001037 case lltok::kw_linker_private_weak:
1038 Res = GlobalValue::LinkerPrivateWeakLinkage;
1039 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001040 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1041 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1042 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1043 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1044 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001045 case lltok::kw_available_externally:
1046 Res = GlobalValue::AvailableExternallyLinkage;
1047 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001048 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1049 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1050 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1051 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1052 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1053 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001054 }
1055 Lex.Lex();
1056 HasLinkage = true;
1057 return false;
1058}
1059
1060/// ParseOptionalVisibility
1061/// ::= /*empty*/
1062/// ::= 'default'
1063/// ::= 'hidden'
1064/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001065///
Chris Lattnerdf986172009-01-02 07:01:27 +00001066bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1067 switch (Lex.getKind()) {
1068 default: Res = GlobalValue::DefaultVisibility; return false;
1069 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1070 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1071 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1072 }
1073 Lex.Lex();
1074 return false;
1075}
1076
1077/// ParseOptionalCallingConv
1078/// ::= /*empty*/
1079/// ::= 'ccc'
1080/// ::= 'fastcc'
1081/// ::= 'coldcc'
1082/// ::= 'x86_stdcallcc'
1083/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001084/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001085/// ::= 'arm_apcscc'
1086/// ::= 'arm_aapcscc'
1087/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001088/// ::= 'msp430_intrcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001089/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001090///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001091bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001092 switch (Lex.getKind()) {
1093 default: CC = CallingConv::C; return false;
1094 case lltok::kw_ccc: CC = CallingConv::C; break;
1095 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1096 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1097 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1098 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001099 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001100 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1101 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1102 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001103 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001104 case lltok::kw_cc: {
1105 unsigned ArbitraryCC;
1106 Lex.Lex();
1107 if (ParseUInt32(ArbitraryCC)) {
1108 return true;
1109 } else
1110 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1111 return false;
1112 }
1113 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001114 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001115
Chris Lattnerdf986172009-01-02 07:01:27 +00001116 Lex.Lex();
1117 return false;
1118}
1119
Chris Lattnerb8c46862009-12-30 05:31:19 +00001120/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001121/// ::= !dbg !42 (',' !dbg !57)*
Chris Lattnerfe805242010-04-01 04:51:13 +00001122bool LLParser::ParseInstructionMetadata(Instruction *Inst) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001123 do {
1124 if (Lex.getKind() != lltok::MetadataVar)
1125 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001126
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001127 std::string Name = Lex.getStrVal();
1128 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001129
Chris Lattner442ffa12009-12-29 21:53:55 +00001130 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001131 unsigned NodeID;
1132 SMLoc Loc = Lex.getLoc();
Chris Lattnere434d272009-12-30 04:56:59 +00001133 if (ParseToken(lltok::exclaim, "expected '!' here") ||
Chris Lattner449c3102010-04-01 05:14:45 +00001134 ParseMDNodeID(Node, NodeID))
Chris Lattnere434d272009-12-30 04:56:59 +00001135 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001136
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001137 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner449c3102010-04-01 05:14:45 +00001138 if (Node) {
1139 // If we got the node, add it to the instruction.
1140 Inst->setMetadata(MDK, Node);
1141 } else {
1142 MDRef R = { Loc, MDK, NodeID };
1143 // Otherwise, remember that this should be resolved later.
1144 ForwardRefInstMetadata[Inst].push_back(R);
1145 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001146
1147 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001148 } while (EatIfPresent(lltok::comma));
1149 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001150}
1151
Chris Lattnerdf986172009-01-02 07:01:27 +00001152/// ParseOptionalAlignment
1153/// ::= /* empty */
1154/// ::= 'align' 4
1155bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1156 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001157 if (!EatIfPresent(lltok::kw_align))
1158 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001159 LocTy AlignLoc = Lex.getLoc();
1160 if (ParseUInt32(Alignment)) return true;
1161 if (!isPowerOf2_32(Alignment))
1162 return Error(AlignLoc, "alignment is not a power of two");
1163 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001164}
1165
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001166/// ParseOptionalCommaAlign
1167/// ::=
1168/// ::= ',' align 4
1169///
1170/// This returns with AteExtraComma set to true if it ate an excess comma at the
1171/// end.
1172bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1173 bool &AteExtraComma) {
1174 AteExtraComma = false;
1175 while (EatIfPresent(lltok::comma)) {
1176 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001177 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001178 AteExtraComma = true;
1179 return false;
1180 }
1181
Chris Lattner093eed12010-04-23 00:50:50 +00001182 if (Lex.getKind() != lltok::kw_align)
1183 return Error(Lex.getLoc(), "expected metadata or 'align'");
1184
1185 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001186 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001187
Devang Patelf633a062009-09-17 23:04:48 +00001188 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001189}
1190
Charles Davis1e063d12010-02-12 00:31:15 +00001191/// ParseOptionalStackAlignment
1192/// ::= /* empty */
1193/// ::= 'alignstack' '(' 4 ')'
1194bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1195 Alignment = 0;
1196 if (!EatIfPresent(lltok::kw_alignstack))
1197 return false;
1198 LocTy ParenLoc = Lex.getLoc();
1199 if (!EatIfPresent(lltok::lparen))
1200 return Error(ParenLoc, "expected '('");
1201 LocTy AlignLoc = Lex.getLoc();
1202 if (ParseUInt32(Alignment)) return true;
1203 ParenLoc = Lex.getLoc();
1204 if (!EatIfPresent(lltok::rparen))
1205 return Error(ParenLoc, "expected ')'");
1206 if (!isPowerOf2_32(Alignment))
1207 return Error(AlignLoc, "stack alignment is not a power of two");
1208 return false;
1209}
Devang Patelf633a062009-09-17 23:04:48 +00001210
Chris Lattner628c13a2009-12-30 05:14:00 +00001211/// ParseIndexList - This parses the index list for an insert/extractvalue
1212/// instruction. This sets AteExtraComma in the case where we eat an extra
1213/// comma at the end of the line and find that it is followed by metadata.
1214/// Clients that don't allow metadata can call the version of this function that
1215/// only takes one argument.
1216///
Chris Lattnerdf986172009-01-02 07:01:27 +00001217/// ParseIndexList
1218/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001219///
1220bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1221 bool &AteExtraComma) {
1222 AteExtraComma = false;
1223
Chris Lattnerdf986172009-01-02 07:01:27 +00001224 if (Lex.getKind() != lltok::comma)
1225 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001226
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001227 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001228 if (Lex.getKind() == lltok::MetadataVar) {
1229 AteExtraComma = true;
1230 return false;
1231 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001232 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001233 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001234 Indices.push_back(Idx);
1235 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001236
Chris Lattnerdf986172009-01-02 07:01:27 +00001237 return false;
1238}
1239
1240//===----------------------------------------------------------------------===//
1241// Type Parsing.
1242//===----------------------------------------------------------------------===//
1243
1244/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001245bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1246 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001247 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001248
Chris Lattnerdf986172009-01-02 07:01:27 +00001249 // Verify no unresolved uprefs.
1250 if (!UpRefs.empty())
1251 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001252
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001253 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001254 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001255
Chris Lattnerdf986172009-01-02 07:01:27 +00001256 return false;
1257}
1258
1259/// HandleUpRefs - Every time we finish a new layer of types, this function is
1260/// called. It loops through the UpRefs vector, which is a list of the
1261/// currently active types. For each type, if the up-reference is contained in
1262/// the newly completed type, we decrement the level count. When the level
1263/// count reaches zero, the up-referenced type is the type that is passed in:
1264/// thus we can complete the cycle.
1265///
1266PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1267 // If Ty isn't abstract, or if there are no up-references in it, then there is
1268 // nothing to resolve here.
1269 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001270
Chris Lattnerdf986172009-01-02 07:01:27 +00001271 PATypeHolder Ty(ty);
1272#if 0
David Greene0e28d762009-12-23 23:38:28 +00001273 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001274 << "' newly formed. Resolving upreferences.\n"
1275 << UpRefs.size() << " upreferences active!\n";
1276#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001277
Chris Lattnerdf986172009-01-02 07:01:27 +00001278 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1279 // to zero), we resolve them all together before we resolve them to Ty. At
1280 // the end of the loop, if there is anything to resolve to Ty, it will be in
1281 // this variable.
1282 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001283
Chris Lattnerdf986172009-01-02 07:01:27 +00001284 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1285 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1286 bool ContainsType =
1287 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1288 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001289
Chris Lattnerdf986172009-01-02 07:01:27 +00001290#if 0
David Greene0e28d762009-12-23 23:38:28 +00001291 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001292 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1293 << (ContainsType ? "true" : "false")
1294 << " level=" << UpRefs[i].NestingLevel << "\n";
1295#endif
1296 if (!ContainsType)
1297 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001298
Chris Lattnerdf986172009-01-02 07:01:27 +00001299 // Decrement level of upreference
1300 unsigned Level = --UpRefs[i].NestingLevel;
1301 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001302
Chris Lattnerdf986172009-01-02 07:01:27 +00001303 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1304 if (Level != 0)
1305 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001306
Chris Lattnerdf986172009-01-02 07:01:27 +00001307#if 0
David Greene0e28d762009-12-23 23:38:28 +00001308 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001309#endif
1310 if (!TypeToResolve)
1311 TypeToResolve = UpRefs[i].UpRefTy;
1312 else
1313 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1314 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1315 --i; // Do not skip the next element.
1316 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001317
Chris Lattnerdf986172009-01-02 07:01:27 +00001318 if (TypeToResolve)
1319 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001320
Chris Lattnerdf986172009-01-02 07:01:27 +00001321 return Ty;
1322}
1323
1324
1325/// ParseTypeRec - The recursive function used to process the internal
1326/// implementation details of types.
1327bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1328 switch (Lex.getKind()) {
1329 default:
1330 return TokError("expected type");
1331 case lltok::Type:
1332 // TypeRec ::= 'float' | 'void' (etc)
1333 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001334 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001335 break;
1336 case lltok::kw_opaque:
1337 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001338 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001339 Lex.Lex();
1340 break;
1341 case lltok::lbrace:
1342 // TypeRec ::= '{' ... '}'
1343 if (ParseStructType(Result, false))
1344 return true;
1345 break;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001346 case lltok::kw_union:
1347 // TypeRec ::= 'union' '{' ... '}'
1348 if (ParseUnionType(Result))
1349 return true;
1350 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001351 case lltok::lsquare:
1352 // TypeRec ::= '[' ... ']'
1353 Lex.Lex(); // eat the lsquare.
1354 if (ParseArrayVectorType(Result, false))
1355 return true;
1356 break;
1357 case lltok::less: // Either vector or packed struct.
1358 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001359 Lex.Lex();
1360 if (Lex.getKind() == lltok::lbrace) {
1361 if (ParseStructType(Result, true) ||
1362 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001363 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001364 } else if (ParseArrayVectorType(Result, true))
1365 return true;
1366 break;
1367 case lltok::LocalVar:
1368 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1369 // TypeRec ::= %foo
1370 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1371 Result = T;
1372 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001373 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001374 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1375 std::make_pair(Result,
1376 Lex.getLoc())));
1377 M->addTypeName(Lex.getStrVal(), Result.get());
1378 }
1379 Lex.Lex();
1380 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001381
Chris Lattnerdf986172009-01-02 07:01:27 +00001382 case lltok::LocalVarID:
1383 // TypeRec ::= %4
1384 if (Lex.getUIntVal() < NumberedTypes.size())
1385 Result = NumberedTypes[Lex.getUIntVal()];
1386 else {
1387 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1388 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1389 if (I != ForwardRefTypeIDs.end())
1390 Result = I->second.first;
1391 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001392 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001393 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1394 std::make_pair(Result,
1395 Lex.getLoc())));
1396 }
1397 }
1398 Lex.Lex();
1399 break;
1400 case lltok::backslash: {
1401 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001402 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001403 unsigned Val;
1404 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001405 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001406 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1407 Result = OT;
1408 break;
1409 }
1410 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001411
1412 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001413 while (1) {
1414 switch (Lex.getKind()) {
1415 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001416 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001417
1418 // TypeRec ::= TypeRec '*'
1419 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001420 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001421 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001422 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001423 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001424 if (!PointerType::isValidElementType(Result.get()))
1425 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001426 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001427 Lex.Lex();
1428 break;
1429
1430 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1431 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001432 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001433 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001434 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001435 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001436 if (!PointerType::isValidElementType(Result.get()))
1437 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001438 unsigned AddrSpace;
1439 if (ParseOptionalAddrSpace(AddrSpace) ||
1440 ParseToken(lltok::star, "expected '*' in address space"))
1441 return true;
1442
Owen Andersondebcb012009-07-29 22:17:13 +00001443 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001444 break;
1445 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001446
Chris Lattnerdf986172009-01-02 07:01:27 +00001447 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1448 case lltok::lparen:
1449 if (ParseFunctionType(Result))
1450 return true;
1451 break;
1452 }
1453 }
1454}
1455
1456/// ParseParameterList
1457/// ::= '(' ')'
1458/// ::= '(' Arg (',' Arg)* ')'
1459/// Arg
1460/// ::= Type OptionalAttributes Value OptionalAttributes
1461bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1462 PerFunctionState &PFS) {
1463 if (ParseToken(lltok::lparen, "expected '(' in call"))
1464 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001465
Chris Lattnerdf986172009-01-02 07:01:27 +00001466 while (Lex.getKind() != lltok::rparen) {
1467 // If this isn't the first argument, we need a comma.
1468 if (!ArgList.empty() &&
1469 ParseToken(lltok::comma, "expected ',' in argument list"))
1470 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001471
Chris Lattnerdf986172009-01-02 07:01:27 +00001472 // Parse the argument.
1473 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001474 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001475 unsigned ArgAttrs1 = Attribute::None;
1476 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001477 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001478 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001479 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001480
Chris Lattner287881d2009-12-30 02:11:14 +00001481 // Otherwise, handle normal operands.
1482 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1483 ParseValue(ArgTy, V, PFS) ||
1484 // FIXME: Should not allow attributes after the argument, remove this
1485 // in LLVM 3.0.
1486 ParseOptionalAttrs(ArgAttrs2, 3))
1487 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001488 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1489 }
1490
1491 Lex.Lex(); // Lex the ')'.
1492 return false;
1493}
1494
1495
1496
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001497/// ParseArgumentList - Parse the argument list for a function type or function
1498/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001499/// ::= '(' ArgTypeListI ')'
1500/// ArgTypeListI
1501/// ::= /*empty*/
1502/// ::= '...'
1503/// ::= ArgTypeList ',' '...'
1504/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001505///
Chris Lattnerdf986172009-01-02 07:01:27 +00001506bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001507 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001508 isVarArg = false;
1509 assert(Lex.getKind() == lltok::lparen);
1510 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001511
Chris Lattnerdf986172009-01-02 07:01:27 +00001512 if (Lex.getKind() == lltok::rparen) {
1513 // empty
1514 } else if (Lex.getKind() == lltok::dotdotdot) {
1515 isVarArg = true;
1516 Lex.Lex();
1517 } else {
1518 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001519 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001520 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001521 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001522
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001523 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1524 // types (such as a function returning a pointer to itself). If parsing a
1525 // function prototype, we require fully resolved types.
1526 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001527 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001528
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001529 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001530 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001531
Chris Lattnerdf986172009-01-02 07:01:27 +00001532 if (Lex.getKind() == lltok::LocalVar ||
1533 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1534 Name = Lex.getStrVal();
1535 Lex.Lex();
1536 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001537
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001538 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001539 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001540
Chris Lattnerdf986172009-01-02 07:01:27 +00001541 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001542
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001543 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001544 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001545 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001546 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001547 break;
1548 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001549
Chris Lattnerdf986172009-01-02 07:01:27 +00001550 // Otherwise must be an argument type.
1551 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001552 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001553 ParseOptionalAttrs(Attrs, 0)) return true;
1554
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001555 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001556 return Error(TypeLoc, "argument can not have void type");
1557
Chris Lattnerdf986172009-01-02 07:01:27 +00001558 if (Lex.getKind() == lltok::LocalVar ||
1559 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1560 Name = Lex.getStrVal();
1561 Lex.Lex();
1562 } else {
1563 Name = "";
1564 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001565
Duncan Sands47c51882010-02-16 14:50:09 +00001566 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001567 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001568
Chris Lattnerdf986172009-01-02 07:01:27 +00001569 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1570 }
1571 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001572
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001573 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001574}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001575
Chris Lattnerdf986172009-01-02 07:01:27 +00001576/// ParseFunctionType
1577/// ::= Type ArgumentList OptionalAttrs
1578bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1579 assert(Lex.getKind() == lltok::lparen);
1580
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001581 if (!FunctionType::isValidReturnType(Result))
1582 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001583
Chris Lattnerdf986172009-01-02 07:01:27 +00001584 std::vector<ArgInfo> ArgList;
1585 bool isVarArg;
1586 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001587 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001588 // FIXME: Allow, but ignore attributes on function types!
1589 // FIXME: Remove in LLVM 3.0
1590 ParseOptionalAttrs(Attrs, 2))
1591 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001592
Chris Lattnerdf986172009-01-02 07:01:27 +00001593 // Reject names on the arguments lists.
1594 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1595 if (!ArgList[i].Name.empty())
1596 return Error(ArgList[i].Loc, "argument name invalid in function type");
1597 if (!ArgList[i].Attrs != 0) {
1598 // Allow but ignore attributes on function types; this permits
1599 // auto-upgrade.
1600 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1601 }
1602 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001603
Chris Lattnerdf986172009-01-02 07:01:27 +00001604 std::vector<const Type*> ArgListTy;
1605 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1606 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001607
Owen Andersondebcb012009-07-29 22:17:13 +00001608 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001609 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001610 return false;
1611}
1612
1613/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1614/// TypeRec
1615/// ::= '{' '}'
1616/// ::= '{' TypeRec (',' TypeRec)* '}'
1617/// ::= '<' '{' '}' '>'
1618/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1619bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1620 assert(Lex.getKind() == lltok::lbrace);
1621 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001622
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001623 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001624 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001625 return false;
1626 }
1627
1628 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001629 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001630 if (ParseTypeRec(Result)) return true;
1631 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001632
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001633 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001634 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001635 if (!StructType::isValidElementType(Result))
1636 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001637
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001638 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001639 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001640 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001641
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001642 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001643 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001644 if (!StructType::isValidElementType(Result))
1645 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001646
Chris Lattnerdf986172009-01-02 07:01:27 +00001647 ParamsList.push_back(Result);
1648 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001649
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001650 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1651 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001652
Chris Lattnerdf986172009-01-02 07:01:27 +00001653 std::vector<const Type*> ParamsListTy;
1654 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1655 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001656 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001657 return false;
1658}
1659
Chris Lattnerfdfeb692010-02-12 20:49:41 +00001660/// ParseUnionType
1661/// TypeRec
1662/// ::= 'union' '{' TypeRec (',' TypeRec)* '}'
1663bool LLParser::ParseUnionType(PATypeHolder &Result) {
1664 assert(Lex.getKind() == lltok::kw_union);
1665 Lex.Lex(); // Consume the 'union'
1666
1667 if (ParseToken(lltok::lbrace, "'{' expected after 'union'")) return true;
1668
1669 SmallVector<PATypeHolder, 8> ParamsList;
1670 do {
1671 LocTy EltTyLoc = Lex.getLoc();
1672 if (ParseTypeRec(Result)) return true;
1673 ParamsList.push_back(Result);
1674
1675 if (Result->isVoidTy())
1676 return Error(EltTyLoc, "union element can not have void type");
1677 if (!UnionType::isValidElementType(Result))
1678 return Error(EltTyLoc, "invalid element type for union");
1679
1680 } while (EatIfPresent(lltok::comma)) ;
1681
1682 if (ParseToken(lltok::rbrace, "expected '}' at end of union"))
1683 return true;
1684
1685 SmallVector<const Type*, 8> ParamsListTy;
1686 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1687 ParamsListTy.push_back(ParamsList[i].get());
1688 Result = HandleUpRefs(UnionType::get(&ParamsListTy[0], ParamsListTy.size()));
1689 return false;
1690}
1691
Chris Lattnerdf986172009-01-02 07:01:27 +00001692/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1693/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001694/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001695/// ::= '[' APSINTVAL 'x' Types ']'
1696/// ::= '<' APSINTVAL 'x' Types '>'
1697bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1698 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1699 Lex.getAPSIntVal().getBitWidth() > 64)
1700 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001701
Chris Lattnerdf986172009-01-02 07:01:27 +00001702 LocTy SizeLoc = Lex.getLoc();
1703 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001704 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001705
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001706 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1707 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001708
1709 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001710 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001711 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001712
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001713 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001714 return Error(TypeLoc, "array and vector element type cannot be void");
1715
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001716 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1717 "expected end of sequential type"))
1718 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001719
Chris Lattnerdf986172009-01-02 07:01:27 +00001720 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001721 if (Size == 0)
1722 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001723 if ((unsigned)Size != Size)
1724 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001725 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001726 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001727 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001728 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001729 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001730 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001731 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001732 }
1733 return false;
1734}
1735
1736//===----------------------------------------------------------------------===//
1737// Function Semantic Analysis.
1738//===----------------------------------------------------------------------===//
1739
Chris Lattner09d9ef42009-10-28 03:39:23 +00001740LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1741 int functionNumber)
1742 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001743
1744 // Insert unnamed arguments into the NumberedVals list.
1745 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1746 AI != E; ++AI)
1747 if (!AI->hasName())
1748 NumberedVals.push_back(AI);
1749}
1750
1751LLParser::PerFunctionState::~PerFunctionState() {
1752 // If there were any forward referenced non-basicblock values, delete them.
1753 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1754 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1755 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001756 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001757 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001758 delete I->second.first;
1759 I->second.first = 0;
1760 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001761
Chris Lattnerdf986172009-01-02 07:01:27 +00001762 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1763 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1764 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001765 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001766 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001767 delete I->second.first;
1768 I->second.first = 0;
1769 }
1770}
1771
Chris Lattner09d9ef42009-10-28 03:39:23 +00001772bool LLParser::PerFunctionState::FinishFunction() {
1773 // Check to see if someone took the address of labels in this block.
1774 if (!P.ForwardRefBlockAddresses.empty()) {
1775 ValID FunctionID;
1776 if (!F.getName().empty()) {
1777 FunctionID.Kind = ValID::t_GlobalName;
1778 FunctionID.StrVal = F.getName();
1779 } else {
1780 FunctionID.Kind = ValID::t_GlobalID;
1781 FunctionID.UIntVal = FunctionNumber;
1782 }
1783
1784 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1785 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1786 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1787 // Resolve all these references.
1788 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1789 return true;
1790
1791 P.ForwardRefBlockAddresses.erase(FRBAI);
1792 }
1793 }
1794
Chris Lattnerdf986172009-01-02 07:01:27 +00001795 if (!ForwardRefVals.empty())
1796 return P.Error(ForwardRefVals.begin()->second.second,
1797 "use of undefined value '%" + ForwardRefVals.begin()->first +
1798 "'");
1799 if (!ForwardRefValIDs.empty())
1800 return P.Error(ForwardRefValIDs.begin()->second.second,
1801 "use of undefined value '%" +
1802 utostr(ForwardRefValIDs.begin()->first) + "'");
1803 return false;
1804}
1805
1806
1807/// GetVal - Get a value with the specified name or ID, creating a
1808/// forward reference record if needed. This can return null if the value
1809/// exists but does not have the right type.
1810Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1811 const Type *Ty, LocTy Loc) {
1812 // Look this name up in the normal function symbol table.
1813 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001814
Chris Lattnerdf986172009-01-02 07:01:27 +00001815 // If this is a forward reference for the value, see if we already created a
1816 // forward ref record.
1817 if (Val == 0) {
1818 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1819 I = ForwardRefVals.find(Name);
1820 if (I != ForwardRefVals.end())
1821 Val = I->second.first;
1822 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001823
Chris Lattnerdf986172009-01-02 07:01:27 +00001824 // If we have the value in the symbol table or fwd-ref table, return it.
1825 if (Val) {
1826 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001827 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001828 P.Error(Loc, "'%" + Name + "' is not a basic block");
1829 else
1830 P.Error(Loc, "'%" + Name + "' defined with type '" +
1831 Val->getType()->getDescription() + "'");
1832 return 0;
1833 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001834
Chris Lattnerdf986172009-01-02 07:01:27 +00001835 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001836 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001837 P.Error(Loc, "invalid use of a non-first-class type");
1838 return 0;
1839 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001840
Chris Lattnerdf986172009-01-02 07:01:27 +00001841 // Otherwise, create a new forward reference for this value and remember it.
1842 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001843 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001844 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001845 else
1846 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001847
Chris Lattnerdf986172009-01-02 07:01:27 +00001848 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1849 return FwdVal;
1850}
1851
1852Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1853 LocTy Loc) {
1854 // Look this name up in the normal function symbol table.
1855 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001856
Chris Lattnerdf986172009-01-02 07:01:27 +00001857 // If this is a forward reference for the value, see if we already created a
1858 // forward ref record.
1859 if (Val == 0) {
1860 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1861 I = ForwardRefValIDs.find(ID);
1862 if (I != ForwardRefValIDs.end())
1863 Val = I->second.first;
1864 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001865
Chris Lattnerdf986172009-01-02 07:01:27 +00001866 // If we have the value in the symbol table or fwd-ref table, return it.
1867 if (Val) {
1868 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001869 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001870 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1871 else
1872 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1873 Val->getType()->getDescription() + "'");
1874 return 0;
1875 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001876
Duncan Sands47c51882010-02-16 14:50:09 +00001877 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001878 P.Error(Loc, "invalid use of a non-first-class type");
1879 return 0;
1880 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001881
Chris Lattnerdf986172009-01-02 07:01:27 +00001882 // Otherwise, create a new forward reference for this value and remember it.
1883 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001884 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001885 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001886 else
1887 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001888
Chris Lattnerdf986172009-01-02 07:01:27 +00001889 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1890 return FwdVal;
1891}
1892
1893/// SetInstName - After an instruction is parsed and inserted into its
1894/// basic block, this installs its name.
1895bool LLParser::PerFunctionState::SetInstName(int NameID,
1896 const std::string &NameStr,
1897 LocTy NameLoc, Instruction *Inst) {
1898 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001899 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001900 if (NameID != -1 || !NameStr.empty())
1901 return P.Error(NameLoc, "instructions returning void cannot have a name");
1902 return false;
1903 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001904
Chris Lattnerdf986172009-01-02 07:01:27 +00001905 // If this was a numbered instruction, verify that the instruction is the
1906 // expected value and resolve any forward references.
1907 if (NameStr.empty()) {
1908 // If neither a name nor an ID was specified, just use the next ID.
1909 if (NameID == -1)
1910 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001911
Chris Lattnerdf986172009-01-02 07:01:27 +00001912 if (unsigned(NameID) != NumberedVals.size())
1913 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1914 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001915
Chris Lattnerdf986172009-01-02 07:01:27 +00001916 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1917 ForwardRefValIDs.find(NameID);
1918 if (FI != ForwardRefValIDs.end()) {
1919 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001920 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001921 FI->second.first->getType()->getDescription() + "'");
1922 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001923 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001924 ForwardRefValIDs.erase(FI);
1925 }
1926
1927 NumberedVals.push_back(Inst);
1928 return false;
1929 }
1930
1931 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1932 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1933 FI = ForwardRefVals.find(NameStr);
1934 if (FI != ForwardRefVals.end()) {
1935 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001936 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001937 FI->second.first->getType()->getDescription() + "'");
1938 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001939 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001940 ForwardRefVals.erase(FI);
1941 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001942
Chris Lattnerdf986172009-01-02 07:01:27 +00001943 // Set the name on the instruction.
1944 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001945
Chris Lattnerdf986172009-01-02 07:01:27 +00001946 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001947 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001948 NameStr + "'");
1949 return false;
1950}
1951
1952/// GetBB - Get a basic block with the specified name or ID, creating a
1953/// forward reference record if needed.
1954BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1955 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001956 return cast_or_null<BasicBlock>(GetVal(Name,
1957 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001958}
1959
1960BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001961 return cast_or_null<BasicBlock>(GetVal(ID,
1962 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001963}
1964
1965/// DefineBB - Define the specified basic block, which is either named or
1966/// unnamed. If there is an error, this returns null otherwise it returns
1967/// the block being defined.
1968BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1969 LocTy Loc) {
1970 BasicBlock *BB;
1971 if (Name.empty())
1972 BB = GetBB(NumberedVals.size(), Loc);
1973 else
1974 BB = GetBB(Name, Loc);
1975 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001976
Chris Lattnerdf986172009-01-02 07:01:27 +00001977 // Move the block to the end of the function. Forward ref'd blocks are
1978 // inserted wherever they happen to be referenced.
1979 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001980
Chris Lattnerdf986172009-01-02 07:01:27 +00001981 // Remove the block from forward ref sets.
1982 if (Name.empty()) {
1983 ForwardRefValIDs.erase(NumberedVals.size());
1984 NumberedVals.push_back(BB);
1985 } else {
1986 // BB forward references are already in the function symbol table.
1987 ForwardRefVals.erase(Name);
1988 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001989
Chris Lattnerdf986172009-01-02 07:01:27 +00001990 return BB;
1991}
1992
1993//===----------------------------------------------------------------------===//
1994// Constants.
1995//===----------------------------------------------------------------------===//
1996
1997/// ParseValID - Parse an abstract value that doesn't necessarily have a
1998/// type implied. For example, if we parse "4" we don't know what integer type
1999/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00002000/// sanity. PFS is used to convert function-local operands of metadata (since
2001/// metadata operands are not just parsed here but also converted to values).
2002/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00002003bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002004 ID.Loc = Lex.getLoc();
2005 switch (Lex.getKind()) {
2006 default: return TokError("expected value token");
2007 case lltok::GlobalID: // @42
2008 ID.UIntVal = Lex.getUIntVal();
2009 ID.Kind = ValID::t_GlobalID;
2010 break;
2011 case lltok::GlobalVar: // @foo
2012 ID.StrVal = Lex.getStrVal();
2013 ID.Kind = ValID::t_GlobalName;
2014 break;
2015 case lltok::LocalVarID: // %42
2016 ID.UIntVal = Lex.getUIntVal();
2017 ID.Kind = ValID::t_LocalID;
2018 break;
2019 case lltok::LocalVar: // %foo
2020 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2021 ID.StrVal = Lex.getStrVal();
2022 ID.Kind = ValID::t_LocalName;
2023 break;
Chris Lattnere434d272009-12-30 04:56:59 +00002024 case lltok::exclaim: // !{...} MDNode, !"foo" MDString
Nick Lewycky21cc4462009-04-04 07:22:01 +00002025 Lex.Lex();
Chris Lattner442ffa12009-12-29 21:53:55 +00002026
Chris Lattner3f5132a2009-12-29 22:40:21 +00002027 if (EatIfPresent(lltok::lbrace)) {
Nick Lewyckycb337992009-05-10 20:57:05 +00002028 SmallVector<Value*, 16> Elts;
Victor Hernandez24e64df2010-01-10 07:14:18 +00002029 if (ParseMDNodeVector(Elts, PFS) ||
Nick Lewycky21cc4462009-04-04 07:22:01 +00002030 ParseToken(lltok::rbrace, "expected end of metadata node"))
2031 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00002032
Victor Hernandez24e64df2010-01-10 07:14:18 +00002033 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner287881d2009-12-30 02:11:14 +00002034 ID.Kind = ValID::t_MDNode;
Nick Lewycky21cc4462009-04-04 07:22:01 +00002035 return false;
2036 }
2037
Devang Patel923078c2009-07-01 19:21:12 +00002038 // Standalone metadata reference
2039 // !{ ..., !42, ... }
Chris Lattner860775c2009-12-30 04:13:37 +00002040 if (Lex.getKind() == lltok::APSInt) {
Chris Lattner4a72efc2009-12-30 04:15:23 +00002041 if (ParseMDNodeID(ID.MDNodeVal)) return true;
Chris Lattner287881d2009-12-30 02:11:14 +00002042 ID.Kind = ValID::t_MDNode;
Devang Patel923078c2009-07-01 19:21:12 +00002043 return false;
Chris Lattner287881d2009-12-30 02:11:14 +00002044 }
2045
Nick Lewycky21cc4462009-04-04 07:22:01 +00002046 // MDString:
2047 // ::= '!' STRINGCONSTANT
Chris Lattner287881d2009-12-30 02:11:14 +00002048 if (ParseMDString(ID.MDStringVal)) return true;
2049 ID.Kind = ValID::t_MDString;
Nick Lewycky21cc4462009-04-04 07:22:01 +00002050 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002051 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002052 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002053 ID.Kind = ValID::t_APSInt;
2054 break;
2055 case lltok::APFloat:
2056 ID.APFloatVal = Lex.getAPFloatVal();
2057 ID.Kind = ValID::t_APFloat;
2058 break;
2059 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002060 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002061 ID.Kind = ValID::t_Constant;
2062 break;
2063 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002064 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002065 ID.Kind = ValID::t_Constant;
2066 break;
2067 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2068 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2069 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002070
Chris Lattnerdf986172009-01-02 07:01:27 +00002071 case lltok::lbrace: {
2072 // ValID ::= '{' ConstVector '}'
2073 Lex.Lex();
2074 SmallVector<Constant*, 16> Elts;
2075 if (ParseGlobalValueVector(Elts) ||
2076 ParseToken(lltok::rbrace, "expected end of struct constant"))
2077 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002078
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002079 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2080 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002081 ID.Kind = ValID::t_Constant;
2082 return false;
2083 }
2084 case lltok::less: {
2085 // ValID ::= '<' ConstVector '>' --> Vector.
2086 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2087 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002088 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002089
Chris Lattnerdf986172009-01-02 07:01:27 +00002090 SmallVector<Constant*, 16> Elts;
2091 LocTy FirstEltLoc = Lex.getLoc();
2092 if (ParseGlobalValueVector(Elts) ||
2093 (isPackedStruct &&
2094 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2095 ParseToken(lltok::greater, "expected end of constant"))
2096 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002097
Chris Lattnerdf986172009-01-02 07:01:27 +00002098 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002099 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002100 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002101 ID.Kind = ValID::t_Constant;
2102 return false;
2103 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002104
Chris Lattnerdf986172009-01-02 07:01:27 +00002105 if (Elts.empty())
2106 return Error(ID.Loc, "constant vector must not be empty");
2107
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002108 if (!Elts[0]->getType()->isIntegerTy() &&
2109 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002110 return Error(FirstEltLoc,
2111 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002112
Chris Lattnerdf986172009-01-02 07:01:27 +00002113 // Verify that all the vector elements have the same type.
2114 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2115 if (Elts[i]->getType() != Elts[0]->getType())
2116 return Error(FirstEltLoc,
2117 "vector element #" + utostr(i) +
2118 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002119
Owen Andersonaf7ec972009-07-28 21:19:26 +00002120 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002121 ID.Kind = ValID::t_Constant;
2122 return false;
2123 }
2124 case lltok::lsquare: { // Array Constant
2125 Lex.Lex();
2126 SmallVector<Constant*, 16> Elts;
2127 LocTy FirstEltLoc = Lex.getLoc();
2128 if (ParseGlobalValueVector(Elts) ||
2129 ParseToken(lltok::rsquare, "expected end of array constant"))
2130 return true;
2131
2132 // Handle empty element.
2133 if (Elts.empty()) {
2134 // Use undef instead of an array because it's inconvenient to determine
2135 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002136 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002137 return false;
2138 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002139
Chris Lattnerdf986172009-01-02 07:01:27 +00002140 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002141 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002142 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002143
Owen Andersondebcb012009-07-29 22:17:13 +00002144 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002145
Chris Lattnerdf986172009-01-02 07:01:27 +00002146 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002147 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002148 if (Elts[i]->getType() != Elts[0]->getType())
2149 return Error(FirstEltLoc,
2150 "array element #" + utostr(i) +
2151 " is not of type '" +Elts[0]->getType()->getDescription());
2152 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002153
Owen Anderson1fd70962009-07-28 18:32:17 +00002154 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002155 ID.Kind = ValID::t_Constant;
2156 return false;
2157 }
2158 case lltok::kw_c: // c "foo"
2159 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002160 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002161 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2162 ID.Kind = ValID::t_Constant;
2163 return false;
2164
2165 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002166 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2167 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002168 Lex.Lex();
2169 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002170 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002171 ParseStringConstant(ID.StrVal) ||
2172 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002173 ParseToken(lltok::StringConstant, "expected constraint string"))
2174 return true;
2175 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002176 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002177 ID.Kind = ValID::t_InlineAsm;
2178 return false;
2179 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002180
Chris Lattner09d9ef42009-10-28 03:39:23 +00002181 case lltok::kw_blockaddress: {
2182 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2183 Lex.Lex();
2184
2185 ValID Fn, Label;
2186 LocTy FnLoc, LabelLoc;
2187
2188 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2189 ParseValID(Fn) ||
2190 ParseToken(lltok::comma, "expected comma in block address expression")||
2191 ParseValID(Label) ||
2192 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2193 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002194
Chris Lattner09d9ef42009-10-28 03:39:23 +00002195 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2196 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002197 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002198 return Error(Label.Loc, "expected basic block name in blockaddress");
2199
2200 // Make a global variable as a placeholder for this reference.
2201 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2202 false, GlobalValue::InternalLinkage,
2203 0, "");
2204 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2205 ID.ConstantVal = FwdRef;
2206 ID.Kind = ValID::t_Constant;
2207 return false;
2208 }
2209
Chris Lattnerdf986172009-01-02 07:01:27 +00002210 case lltok::kw_trunc:
2211 case lltok::kw_zext:
2212 case lltok::kw_sext:
2213 case lltok::kw_fptrunc:
2214 case lltok::kw_fpext:
2215 case lltok::kw_bitcast:
2216 case lltok::kw_uitofp:
2217 case lltok::kw_sitofp:
2218 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002219 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002220 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002221 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002222 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002223 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002224 Constant *SrcVal;
2225 Lex.Lex();
2226 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2227 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002228 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002229 ParseType(DestTy) ||
2230 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2231 return true;
2232 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2233 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2234 SrcVal->getType()->getDescription() + "' to '" +
2235 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002236 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002237 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002238 ID.Kind = ValID::t_Constant;
2239 return false;
2240 }
2241 case lltok::kw_extractvalue: {
2242 Lex.Lex();
2243 Constant *Val;
2244 SmallVector<unsigned, 4> Indices;
2245 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2246 ParseGlobalTypeAndValue(Val) ||
2247 ParseIndexList(Indices) ||
2248 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2249 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002250
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002251 if (!Val->getType()->isAggregateType())
2252 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002253 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2254 Indices.end()))
2255 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002256 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002257 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002258 ID.Kind = ValID::t_Constant;
2259 return false;
2260 }
2261 case lltok::kw_insertvalue: {
2262 Lex.Lex();
2263 Constant *Val0, *Val1;
2264 SmallVector<unsigned, 4> Indices;
2265 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2266 ParseGlobalTypeAndValue(Val0) ||
2267 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2268 ParseGlobalTypeAndValue(Val1) ||
2269 ParseIndexList(Indices) ||
2270 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2271 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002272 if (!Val0->getType()->isAggregateType())
2273 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002274 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2275 Indices.end()))
2276 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002277 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002278 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002279 ID.Kind = ValID::t_Constant;
2280 return false;
2281 }
2282 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002283 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002284 unsigned PredVal, Opc = Lex.getUIntVal();
2285 Constant *Val0, *Val1;
2286 Lex.Lex();
2287 if (ParseCmpPredicate(PredVal, Opc) ||
2288 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2289 ParseGlobalTypeAndValue(Val0) ||
2290 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2291 ParseGlobalTypeAndValue(Val1) ||
2292 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2293 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002294
Chris Lattnerdf986172009-01-02 07:01:27 +00002295 if (Val0->getType() != Val1->getType())
2296 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002297
Chris Lattnerdf986172009-01-02 07:01:27 +00002298 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002299
Chris Lattnerdf986172009-01-02 07:01:27 +00002300 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002301 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002302 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002303 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002304 } else {
2305 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002306 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002307 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002308 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002309 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002310 }
2311 ID.Kind = ValID::t_Constant;
2312 return false;
2313 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002314
Chris Lattnerdf986172009-01-02 07:01:27 +00002315 // Binary Operators.
2316 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002317 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002318 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002319 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002320 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002321 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002322 case lltok::kw_udiv:
2323 case lltok::kw_sdiv:
2324 case lltok::kw_fdiv:
2325 case lltok::kw_urem:
2326 case lltok::kw_srem:
2327 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002328 bool NUW = false;
2329 bool NSW = false;
2330 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002331 unsigned Opc = Lex.getUIntVal();
2332 Constant *Val0, *Val1;
2333 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002334 LocTy ModifierLoc = Lex.getLoc();
2335 if (Opc == Instruction::Add ||
2336 Opc == Instruction::Sub ||
2337 Opc == Instruction::Mul) {
2338 if (EatIfPresent(lltok::kw_nuw))
2339 NUW = true;
2340 if (EatIfPresent(lltok::kw_nsw)) {
2341 NSW = true;
2342 if (EatIfPresent(lltok::kw_nuw))
2343 NUW = true;
2344 }
2345 } else if (Opc == Instruction::SDiv) {
2346 if (EatIfPresent(lltok::kw_exact))
2347 Exact = true;
2348 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002349 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2350 ParseGlobalTypeAndValue(Val0) ||
2351 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2352 ParseGlobalTypeAndValue(Val1) ||
2353 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2354 return true;
2355 if (Val0->getType() != Val1->getType())
2356 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002357 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002358 if (NUW)
2359 return Error(ModifierLoc, "nuw only applies to integer operations");
2360 if (NSW)
2361 return Error(ModifierLoc, "nsw only applies to integer operations");
2362 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002363 // Check that the type is valid for the operator.
2364 switch (Opc) {
2365 case Instruction::Add:
2366 case Instruction::Sub:
2367 case Instruction::Mul:
2368 case Instruction::UDiv:
2369 case Instruction::SDiv:
2370 case Instruction::URem:
2371 case Instruction::SRem:
2372 if (!Val0->getType()->isIntOrIntVectorTy())
2373 return Error(ID.Loc, "constexpr requires integer operands");
2374 break;
2375 case Instruction::FAdd:
2376 case Instruction::FSub:
2377 case Instruction::FMul:
2378 case Instruction::FDiv:
2379 case Instruction::FRem:
2380 if (!Val0->getType()->isFPOrFPVectorTy())
2381 return Error(ID.Loc, "constexpr requires fp operands");
2382 break;
2383 default: llvm_unreachable("Unknown binary operator!");
2384 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002385 unsigned Flags = 0;
2386 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2387 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2388 if (Exact) Flags |= SDivOperator::IsExact;
2389 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002390 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002391 ID.Kind = ValID::t_Constant;
2392 return false;
2393 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002394
Chris Lattnerdf986172009-01-02 07:01:27 +00002395 // Logical Operations
2396 case lltok::kw_shl:
2397 case lltok::kw_lshr:
2398 case lltok::kw_ashr:
2399 case lltok::kw_and:
2400 case lltok::kw_or:
2401 case lltok::kw_xor: {
2402 unsigned Opc = Lex.getUIntVal();
2403 Constant *Val0, *Val1;
2404 Lex.Lex();
2405 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2406 ParseGlobalTypeAndValue(Val0) ||
2407 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2408 ParseGlobalTypeAndValue(Val1) ||
2409 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2410 return true;
2411 if (Val0->getType() != Val1->getType())
2412 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002413 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002414 return Error(ID.Loc,
2415 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002416 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002417 ID.Kind = ValID::t_Constant;
2418 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002419 }
2420
Chris Lattnerdf986172009-01-02 07:01:27 +00002421 case lltok::kw_getelementptr:
2422 case lltok::kw_shufflevector:
2423 case lltok::kw_insertelement:
2424 case lltok::kw_extractelement:
2425 case lltok::kw_select: {
2426 unsigned Opc = Lex.getUIntVal();
2427 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002428 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002429 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002430 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002431 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002432 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2433 ParseGlobalValueVector(Elts) ||
2434 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2435 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002436
Chris Lattnerdf986172009-01-02 07:01:27 +00002437 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002438 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002439 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002440
Chris Lattnerdf986172009-01-02 07:01:27 +00002441 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002442 (Value**)(Elts.data() + 1),
2443 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002444 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002445 ID.ConstantVal = InBounds ?
2446 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2447 Elts.data() + 1,
2448 Elts.size() - 1) :
2449 ConstantExpr::getGetElementPtr(Elts[0],
2450 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002451 } else if (Opc == Instruction::Select) {
2452 if (Elts.size() != 3)
2453 return Error(ID.Loc, "expected three operands to select");
2454 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2455 Elts[2]))
2456 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002457 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002458 } else if (Opc == Instruction::ShuffleVector) {
2459 if (Elts.size() != 3)
2460 return Error(ID.Loc, "expected three operands to shufflevector");
2461 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2462 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002463 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002464 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002465 } else if (Opc == Instruction::ExtractElement) {
2466 if (Elts.size() != 2)
2467 return Error(ID.Loc, "expected two operands to extractelement");
2468 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2469 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002470 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002471 } else {
2472 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2473 if (Elts.size() != 3)
2474 return Error(ID.Loc, "expected three operands to insertelement");
2475 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2476 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002477 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002478 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002479 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002480
Chris Lattnerdf986172009-01-02 07:01:27 +00002481 ID.Kind = ValID::t_Constant;
2482 return false;
2483 }
2484 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002485
Chris Lattnerdf986172009-01-02 07:01:27 +00002486 Lex.Lex();
2487 return false;
2488}
2489
2490/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002491bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2492 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002493 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002494 Value *V = NULL;
2495 bool Parsed = ParseValID(ID) ||
2496 ConvertValIDToValue(Ty, ID, V, NULL);
2497 if (V && !(C = dyn_cast<Constant>(V)))
2498 return Error(ID.Loc, "global values must be constants");
2499 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002500}
2501
Victor Hernandez92f238d2010-01-11 22:31:58 +00002502bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2503 PATypeHolder Type(Type::getVoidTy(Context));
2504 return ParseType(Type) ||
2505 ParseGlobalValue(Type, V);
2506}
2507
2508/// ParseGlobalValueVector
2509/// ::= /*empty*/
2510/// ::= TypeAndValue (',' TypeAndValue)*
2511bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2512 // Empty list.
2513 if (Lex.getKind() == lltok::rbrace ||
2514 Lex.getKind() == lltok::rsquare ||
2515 Lex.getKind() == lltok::greater ||
2516 Lex.getKind() == lltok::rparen)
2517 return false;
2518
2519 Constant *C;
2520 if (ParseGlobalTypeAndValue(C)) return true;
2521 Elts.push_back(C);
2522
2523 while (EatIfPresent(lltok::comma)) {
2524 if (ParseGlobalTypeAndValue(C)) return true;
2525 Elts.push_back(C);
2526 }
2527
2528 return false;
2529}
2530
2531
2532//===----------------------------------------------------------------------===//
2533// Function Parsing.
2534//===----------------------------------------------------------------------===//
2535
2536bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2537 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002538 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002539 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002540
Chris Lattnerdf986172009-01-02 07:01:27 +00002541 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002542 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002543 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002544 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2545 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2546 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002547 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002548 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2549 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2550 return (V == 0);
2551 case ValID::t_InlineAsm: {
2552 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2553 const FunctionType *FTy =
2554 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2555 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2556 return Error(ID.Loc, "invalid type for inline asm constraint string");
2557 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2558 return false;
2559 }
2560 case ValID::t_MDNode:
2561 if (!Ty->isMetadataTy())
2562 return Error(ID.Loc, "metadata value must have metadata type");
2563 V = ID.MDNodeVal;
2564 return false;
2565 case ValID::t_MDString:
2566 if (!Ty->isMetadataTy())
2567 return Error(ID.Loc, "metadata value must have metadata type");
2568 V = ID.MDStringVal;
2569 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002570 case ValID::t_GlobalName:
2571 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2572 return V == 0;
2573 case ValID::t_GlobalID:
2574 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2575 return V == 0;
2576 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002577 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002578 return Error(ID.Loc, "integer constant must have integer type");
2579 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002580 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002581 return false;
2582 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002583 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002584 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2585 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002586
Chris Lattnerdf986172009-01-02 07:01:27 +00002587 // The lexer has no type info, so builds all float and double FP constants
2588 // as double. Fix this here. Long double does not need this.
2589 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002590 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002591 bool Ignored;
2592 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2593 &Ignored);
2594 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002595 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002596
Chris Lattner959873d2009-01-05 18:24:23 +00002597 if (V->getType() != Ty)
2598 return Error(ID.Loc, "floating point constant does not have type '" +
2599 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002600
Chris Lattnerdf986172009-01-02 07:01:27 +00002601 return false;
2602 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002603 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002604 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002605 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002606 return false;
2607 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002608 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002609 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002610 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002611 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002612 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002613 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002614 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002615 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002616 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002617 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002618 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002619 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002620 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002621 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002622 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002623 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002624 return false;
2625 case ValID::t_Constant:
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002626 if (ID.ConstantVal->getType() != Ty) {
2627 // Allow a constant struct with a single member to be converted
2628 // to a union, if the union has a member which is the same type
2629 // as the struct member.
2630 if (const UnionType* utype = dyn_cast<UnionType>(Ty)) {
2631 return ParseUnionValue(utype, ID, V);
2632 }
2633
Chris Lattnerdf986172009-01-02 07:01:27 +00002634 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002635 }
2636
Chris Lattnerdf986172009-01-02 07:01:27 +00002637 V = ID.ConstantVal;
2638 return false;
2639 }
2640}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002641
Chris Lattnerdf986172009-01-02 07:01:27 +00002642bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2643 V = 0;
2644 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002645 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002646 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002647}
2648
2649bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002650 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002651 return ParseType(T) ||
2652 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002653}
2654
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002655bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2656 PerFunctionState &PFS) {
2657 Value *V;
2658 Loc = Lex.getLoc();
2659 if (ParseTypeAndValue(V, PFS)) return true;
2660 if (!isa<BasicBlock>(V))
2661 return Error(Loc, "expected a basic block");
2662 BB = cast<BasicBlock>(V);
2663 return false;
2664}
2665
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002666bool LLParser::ParseUnionValue(const UnionType* utype, ValID &ID, Value *&V) {
2667 if (const StructType* stype = dyn_cast<StructType>(ID.ConstantVal->getType())) {
2668 if (stype->getNumContainedTypes() != 1)
2669 return Error(ID.Loc, "constant expression type mismatch");
2670 int index = utype->getElementTypeIndex(stype->getContainedType(0));
2671 if (index < 0)
2672 return Error(ID.Loc, "initializer type is not a member of the union");
2673
2674 V = ConstantUnion::get(
2675 utype, cast<Constant>(ID.ConstantVal->getOperand(0)));
2676 return false;
2677 }
2678
2679 return Error(ID.Loc, "constant expression type mismatch");
2680}
2681
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002682
Chris Lattnerdf986172009-01-02 07:01:27 +00002683/// FunctionHeader
2684/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2685/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2686/// OptionalAlign OptGC
2687bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2688 // Parse the linkage.
2689 LocTy LinkageLoc = Lex.getLoc();
2690 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002691
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002692 unsigned Visibility, RetAttrs;
2693 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002694 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002695 LocTy RetTypeLoc = Lex.getLoc();
2696 if (ParseOptionalLinkage(Linkage) ||
2697 ParseOptionalVisibility(Visibility) ||
2698 ParseOptionalCallingConv(CC) ||
2699 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002700 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002701 return true;
2702
2703 // Verify that the linkage is ok.
2704 switch ((GlobalValue::LinkageTypes)Linkage) {
2705 case GlobalValue::ExternalLinkage:
2706 break; // always ok.
2707 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002708 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002709 if (isDefine)
2710 return Error(LinkageLoc, "invalid linkage for function definition");
2711 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002712 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002713 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002714 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002715 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002716 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002717 case GlobalValue::LinkOnceAnyLinkage:
2718 case GlobalValue::LinkOnceODRLinkage:
2719 case GlobalValue::WeakAnyLinkage:
2720 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002721 case GlobalValue::DLLExportLinkage:
2722 if (!isDefine)
2723 return Error(LinkageLoc, "invalid linkage for function declaration");
2724 break;
2725 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002726 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002727 return Error(LinkageLoc, "invalid function linkage type");
2728 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002729
Chris Lattner99bb3152009-01-05 08:00:30 +00002730 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002731 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002732 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002733
Chris Lattnerdf986172009-01-02 07:01:27 +00002734 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002735
2736 std::string FunctionName;
2737 if (Lex.getKind() == lltok::GlobalVar) {
2738 FunctionName = Lex.getStrVal();
2739 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2740 unsigned NameID = Lex.getUIntVal();
2741
2742 if (NameID != NumberedVals.size())
2743 return TokError("function expected to be numbered '%" +
2744 utostr(NumberedVals.size()) + "'");
2745 } else {
2746 return TokError("expected function name");
2747 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002748
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002749 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002750
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002751 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002752 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002753
Chris Lattnerdf986172009-01-02 07:01:27 +00002754 std::vector<ArgInfo> ArgList;
2755 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002756 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002757 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002759 std::string GC;
2760
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002761 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002762 ParseOptionalAttrs(FuncAttrs, 2) ||
2763 (EatIfPresent(lltok::kw_section) &&
2764 ParseStringConstant(Section)) ||
2765 ParseOptionalAlignment(Alignment) ||
2766 (EatIfPresent(lltok::kw_gc) &&
2767 ParseStringConstant(GC)))
2768 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002769
2770 // If the alignment was parsed as an attribute, move to the alignment field.
2771 if (FuncAttrs & Attribute::Alignment) {
2772 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2773 FuncAttrs &= ~Attribute::Alignment;
2774 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002775
Chris Lattnerdf986172009-01-02 07:01:27 +00002776 // Okay, if we got here, the function is syntactically valid. Convert types
2777 // and do semantic checks.
2778 std::vector<const Type*> ParamTypeList;
2779 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002780 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002781 // attributes.
2782 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2783 if (FuncAttrs & ObsoleteFuncAttrs) {
2784 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2785 FuncAttrs &= ~ObsoleteFuncAttrs;
2786 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002787
Chris Lattnerdf986172009-01-02 07:01:27 +00002788 if (RetAttrs != Attribute::None)
2789 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002790
Chris Lattnerdf986172009-01-02 07:01:27 +00002791 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2792 ParamTypeList.push_back(ArgList[i].Type);
2793 if (ArgList[i].Attrs != Attribute::None)
2794 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2795 }
2796
2797 if (FuncAttrs != Attribute::None)
2798 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2799
2800 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002801
Benjamin Kramerf0127052010-01-05 13:12:22 +00002802 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002803 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2804
Owen Andersonfba933c2009-07-01 23:57:11 +00002805 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002806 FunctionType::get(RetType, ParamTypeList, isVarArg);
2807 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002808
2809 Fn = 0;
2810 if (!FunctionName.empty()) {
2811 // If this was a definition of a forward reference, remove the definition
2812 // from the forward reference table and fill in the forward ref.
2813 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2814 ForwardRefVals.find(FunctionName);
2815 if (FRVI != ForwardRefVals.end()) {
2816 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002817 if (Fn->getType() != PFT)
2818 return Error(FRVI->second.second, "invalid forward reference to "
2819 "function '" + FunctionName + "' with wrong type!");
2820
Chris Lattnerdf986172009-01-02 07:01:27 +00002821 ForwardRefVals.erase(FRVI);
2822 } else if ((Fn = M->getFunction(FunctionName))) {
2823 // If this function already exists in the symbol table, then it is
2824 // multiply defined. We accept a few cases for old backwards compat.
2825 // FIXME: Remove this stuff for LLVM 3.0.
2826 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2827 (!Fn->isDeclaration() && isDefine)) {
2828 // If the redefinition has different type or different attributes,
2829 // reject it. If both have bodies, reject it.
2830 return Error(NameLoc, "invalid redefinition of function '" +
2831 FunctionName + "'");
2832 } else if (Fn->isDeclaration()) {
2833 // Make sure to strip off any argument names so we can't get conflicts.
2834 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2835 AI != AE; ++AI)
2836 AI->setName("");
2837 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002838 } else if (M->getNamedValue(FunctionName)) {
2839 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002840 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002841
Dan Gohman41905542009-08-29 23:37:49 +00002842 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002843 // If this is a definition of a forward referenced function, make sure the
2844 // types agree.
2845 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2846 = ForwardRefValIDs.find(NumberedVals.size());
2847 if (I != ForwardRefValIDs.end()) {
2848 Fn = cast<Function>(I->second.first);
2849 if (Fn->getType() != PFT)
2850 return Error(NameLoc, "type of definition and forward reference of '@" +
2851 utostr(NumberedVals.size()) +"' disagree");
2852 ForwardRefValIDs.erase(I);
2853 }
2854 }
2855
2856 if (Fn == 0)
2857 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2858 else // Move the forward-reference to the correct spot in the module.
2859 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2860
2861 if (FunctionName.empty())
2862 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002863
Chris Lattnerdf986172009-01-02 07:01:27 +00002864 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2865 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2866 Fn->setCallingConv(CC);
2867 Fn->setAttributes(PAL);
2868 Fn->setAlignment(Alignment);
2869 Fn->setSection(Section);
2870 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002871
Chris Lattnerdf986172009-01-02 07:01:27 +00002872 // Add all of the arguments we parsed to the function.
2873 Function::arg_iterator ArgIt = Fn->arg_begin();
2874 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002875 // If we run out of arguments in the Function prototype, exit early.
2876 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2877 if (ArgIt == Fn->arg_end()) break;
2878
Chris Lattnerdf986172009-01-02 07:01:27 +00002879 // If the argument has a name, insert it into the argument symbol table.
2880 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002881
Chris Lattnerdf986172009-01-02 07:01:27 +00002882 // Set the name, if it conflicted, it will be auto-renamed.
2883 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002884
Chris Lattnerdf986172009-01-02 07:01:27 +00002885 if (ArgIt->getNameStr() != ArgList[i].Name)
2886 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2887 ArgList[i].Name + "'");
2888 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002889
Chris Lattnerdf986172009-01-02 07:01:27 +00002890 return false;
2891}
2892
2893
2894/// ParseFunctionBody
2895/// ::= '{' BasicBlock+ '}'
2896/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2897///
2898bool LLParser::ParseFunctionBody(Function &Fn) {
2899 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2900 return TokError("expected '{' in function body");
2901 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002902
Chris Lattner09d9ef42009-10-28 03:39:23 +00002903 int FunctionNumber = -1;
2904 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2905
2906 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002907
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002908 // We need at least one basic block.
2909 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2910 return TokError("function body requires at least one basic block");
2911
Chris Lattnerdf986172009-01-02 07:01:27 +00002912 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2913 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002914
Chris Lattnerdf986172009-01-02 07:01:27 +00002915 // Eat the }.
2916 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002917
Chris Lattnerdf986172009-01-02 07:01:27 +00002918 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002919 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002920}
2921
2922/// ParseBasicBlock
2923/// ::= LabelStr? Instruction*
2924bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2925 // If this basic block starts out with a name, remember it.
2926 std::string Name;
2927 LocTy NameLoc = Lex.getLoc();
2928 if (Lex.getKind() == lltok::LabelStr) {
2929 Name = Lex.getStrVal();
2930 Lex.Lex();
2931 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002932
Chris Lattnerdf986172009-01-02 07:01:27 +00002933 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2934 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002935
Chris Lattnerdf986172009-01-02 07:01:27 +00002936 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002937
Chris Lattnerdf986172009-01-02 07:01:27 +00002938 // Parse the instructions in this block until we get a terminator.
2939 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002940 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002941 do {
2942 // This instruction may have three possibilities for a name: a) none
2943 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2944 LocTy NameLoc = Lex.getLoc();
2945 int NameID = -1;
2946 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002947
Chris Lattnerdf986172009-01-02 07:01:27 +00002948 if (Lex.getKind() == lltok::LocalVarID) {
2949 NameID = Lex.getUIntVal();
2950 Lex.Lex();
2951 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2952 return true;
2953 } else if (Lex.getKind() == lltok::LocalVar ||
2954 // FIXME: REMOVE IN LLVM 3.0
2955 Lex.getKind() == lltok::StringConstant) {
2956 NameStr = Lex.getStrVal();
2957 Lex.Lex();
2958 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2959 return true;
2960 }
Devang Patelf633a062009-09-17 23:04:48 +00002961
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002962 switch (ParseInstruction(Inst, BB, PFS)) {
2963 default: assert(0 && "Unknown ParseInstruction result!");
2964 case InstError: return true;
2965 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002966 BB->getInstList().push_back(Inst);
2967
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002968 // With a normal result, we check to see if the instruction is followed by
2969 // a comma and metadata.
2970 if (EatIfPresent(lltok::comma))
Chris Lattnerfe805242010-04-01 04:51:13 +00002971 if (ParseInstructionMetadata(Inst))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002972 return true;
2973 break;
2974 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002975 BB->getInstList().push_back(Inst);
2976
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002977 // If the instruction parser ate an extra comma at the end of it, it
2978 // *must* be followed by metadata.
Chris Lattnerfe805242010-04-01 04:51:13 +00002979 if (ParseInstructionMetadata(Inst))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002980 return true;
2981 break;
2982 }
Devang Patelf633a062009-09-17 23:04:48 +00002983
Chris Lattnerdf986172009-01-02 07:01:27 +00002984 // Set the name on the instruction.
2985 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2986 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002987
Chris Lattnerdf986172009-01-02 07:01:27 +00002988 return false;
2989}
2990
2991//===----------------------------------------------------------------------===//
2992// Instruction Parsing.
2993//===----------------------------------------------------------------------===//
2994
2995/// ParseInstruction - Parse one of the many different instructions.
2996///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002997int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2998 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002999 lltok::Kind Token = Lex.getKind();
3000 if (Token == lltok::Eof)
3001 return TokError("found end of file when expecting more instructions");
3002 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003003 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00003004 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003005
Chris Lattnerdf986172009-01-02 07:01:27 +00003006 switch (Token) {
3007 default: return Error(Loc, "expected instruction opcode");
3008 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00003009 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
3010 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003011 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3012 case lltok::kw_br: return ParseBr(Inst, PFS);
3013 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00003014 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003015 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3016 // Binary Operators.
3017 case lltok::kw_add:
3018 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00003019 case lltok::kw_mul: {
3020 bool NUW = false;
3021 bool NSW = false;
3022 LocTy ModifierLoc = Lex.getLoc();
3023 if (EatIfPresent(lltok::kw_nuw))
3024 NUW = true;
3025 if (EatIfPresent(lltok::kw_nsw)) {
3026 NSW = true;
3027 if (EatIfPresent(lltok::kw_nuw))
3028 NUW = true;
3029 }
Dan Gohman1eaac532010-05-03 22:44:19 +00003030 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
Dan Gohman59858cf2009-07-27 16:11:46 +00003031 if (!Result) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003032 if (!Inst->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003033 if (NUW)
3034 return Error(ModifierLoc, "nuw only applies to integer operations");
3035 if (NSW)
3036 return Error(ModifierLoc, "nsw only applies to integer operations");
3037 }
3038 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003039 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003040 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003041 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003042 }
3043 return Result;
3044 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003045 case lltok::kw_fadd:
3046 case lltok::kw_fsub:
3047 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3048
Dan Gohman59858cf2009-07-27 16:11:46 +00003049 case lltok::kw_sdiv: {
3050 bool Exact = false;
3051 if (EatIfPresent(lltok::kw_exact))
3052 Exact = true;
3053 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3054 if (!Result)
3055 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003056 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003057 return Result;
3058 }
3059
Chris Lattnerdf986172009-01-02 07:01:27 +00003060 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00003061 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003062 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003063 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003064 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003065 case lltok::kw_shl:
3066 case lltok::kw_lshr:
3067 case lltok::kw_ashr:
3068 case lltok::kw_and:
3069 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003070 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003071 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003072 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003073 // Casts.
3074 case lltok::kw_trunc:
3075 case lltok::kw_zext:
3076 case lltok::kw_sext:
3077 case lltok::kw_fptrunc:
3078 case lltok::kw_fpext:
3079 case lltok::kw_bitcast:
3080 case lltok::kw_uitofp:
3081 case lltok::kw_sitofp:
3082 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003083 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003084 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003085 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003086 // Other.
3087 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003088 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003089 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3090 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3091 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3092 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3093 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3094 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3095 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003096 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3097 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00003098 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003099 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3100 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3101 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003102 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003103 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003104 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003105 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003106 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003107 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003108 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3109 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3110 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3111 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3112 }
3113}
3114
3115/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3116bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003117 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003118 switch (Lex.getKind()) {
3119 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3120 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3121 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3122 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3123 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3124 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3125 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3126 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3127 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3128 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3129 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3130 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3131 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3132 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3133 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3134 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3135 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3136 }
3137 } else {
3138 switch (Lex.getKind()) {
3139 default: TokError("expected icmp predicate (e.g. 'eq')");
3140 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3141 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3142 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3143 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3144 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3145 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3146 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3147 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3148 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3149 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3150 }
3151 }
3152 Lex.Lex();
3153 return false;
3154}
3155
3156//===----------------------------------------------------------------------===//
3157// Terminator Instructions.
3158//===----------------------------------------------------------------------===//
3159
3160/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003161/// ::= 'ret' void (',' !dbg, !1)*
3162/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3163/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003164/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003165int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3166 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003167 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003168 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003169
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003170 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003171 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003172 return false;
3173 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003174
Chris Lattnerdf986172009-01-02 07:01:27 +00003175 Value *RV;
3176 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003177
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003178 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003179 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003180 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003181 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003182 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003183 } else {
3184 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003185 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3186 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003187 SmallVector<Value*, 8> RVs;
3188 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003189
Devang Patelf633a062009-09-17 23:04:48 +00003190 do {
Devang Patel0475c912009-09-29 00:01:14 +00003191 // If optional custom metadata, e.g. !dbg is seen then this is the
3192 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003193 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003194 break;
3195 if (ParseTypeAndValue(RV, PFS)) return true;
3196 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003197 } while (EatIfPresent(lltok::comma));
3198
3199 RV = UndefValue::get(PFS.getFunction().getReturnType());
3200 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003201 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3202 BB->getInstList().push_back(I);
3203 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003204 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003205 }
3206 }
Devang Patelf633a062009-09-17 23:04:48 +00003207
Owen Anderson1d0be152009-08-13 21:58:54 +00003208 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003209 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003210}
3211
3212
3213/// ParseBr
3214/// ::= 'br' TypeAndValue
3215/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3216bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3217 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003218 Value *Op0;
3219 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003220 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003221
Chris Lattnerdf986172009-01-02 07:01:27 +00003222 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3223 Inst = BranchInst::Create(BB);
3224 return false;
3225 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003226
Owen Anderson1d0be152009-08-13 21:58:54 +00003227 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003228 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003229
Chris Lattnerdf986172009-01-02 07:01:27 +00003230 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003231 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003233 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003234 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003235
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003236 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003237 return false;
3238}
3239
3240/// ParseSwitch
3241/// Instruction
3242/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3243/// JumpTable
3244/// ::= (TypeAndValue ',' TypeAndValue)*
3245bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3246 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003247 Value *Cond;
3248 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003249 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3250 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003251 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003252 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3253 return true;
3254
Duncan Sands1df98592010-02-16 11:11:14 +00003255 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003256 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003257
Chris Lattnerdf986172009-01-02 07:01:27 +00003258 // Parse the jump table pairs.
3259 SmallPtrSet<Value*, 32> SeenCases;
3260 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3261 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003262 Value *Constant;
3263 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003264
Chris Lattnerdf986172009-01-02 07:01:27 +00003265 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3266 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003267 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003268 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003269
Chris Lattnerdf986172009-01-02 07:01:27 +00003270 if (!SeenCases.insert(Constant))
3271 return Error(CondLoc, "duplicate case value in switch");
3272 if (!isa<ConstantInt>(Constant))
3273 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003274
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003275 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003276 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003277
Chris Lattnerdf986172009-01-02 07:01:27 +00003278 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003279
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003280 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003281 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3282 SI->addCase(Table[i].first, Table[i].second);
3283 Inst = SI;
3284 return false;
3285}
3286
Chris Lattnerab21db72009-10-28 00:19:10 +00003287/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003288/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003289/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3290bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003291 LocTy AddrLoc;
3292 Value *Address;
3293 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003294 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3295 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003296 return true;
3297
Duncan Sands1df98592010-02-16 11:11:14 +00003298 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003299 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003300
3301 // Parse the destination list.
3302 SmallVector<BasicBlock*, 16> DestList;
3303
3304 if (Lex.getKind() != lltok::rsquare) {
3305 BasicBlock *DestBB;
3306 if (ParseTypeAndBasicBlock(DestBB, PFS))
3307 return true;
3308 DestList.push_back(DestBB);
3309
3310 while (EatIfPresent(lltok::comma)) {
3311 if (ParseTypeAndBasicBlock(DestBB, PFS))
3312 return true;
3313 DestList.push_back(DestBB);
3314 }
3315 }
3316
3317 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3318 return true;
3319
Chris Lattnerab21db72009-10-28 00:19:10 +00003320 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003321 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3322 IBI->addDestination(DestList[i]);
3323 Inst = IBI;
3324 return false;
3325}
3326
3327
Chris Lattnerdf986172009-01-02 07:01:27 +00003328/// ParseInvoke
3329/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3330/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3331bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3332 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003333 unsigned RetAttrs, FnAttrs;
3334 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003335 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003336 LocTy RetTypeLoc;
3337 ValID CalleeID;
3338 SmallVector<ParamInfo, 16> ArgList;
3339
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003340 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003341 if (ParseOptionalCallingConv(CC) ||
3342 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003343 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003344 ParseValID(CalleeID) ||
3345 ParseParameterList(ArgList, PFS) ||
3346 ParseOptionalAttrs(FnAttrs, 2) ||
3347 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003348 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003349 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003350 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003351 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003352
Chris Lattnerdf986172009-01-02 07:01:27 +00003353 // If RetType is a non-function pointer type, then this is the short syntax
3354 // for the call, which means that RetType is just the return type. Infer the
3355 // rest of the function argument types from the arguments that are present.
3356 const PointerType *PFTy = 0;
3357 const FunctionType *Ty = 0;
3358 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3359 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3360 // Pull out the types of all of the arguments...
3361 std::vector<const Type*> ParamTypes;
3362 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3363 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003364
Chris Lattnerdf986172009-01-02 07:01:27 +00003365 if (!FunctionType::isValidReturnType(RetType))
3366 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003367
Owen Andersondebcb012009-07-29 22:17:13 +00003368 Ty = FunctionType::get(RetType, ParamTypes, false);
3369 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003370 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003371
Chris Lattnerdf986172009-01-02 07:01:27 +00003372 // Look up the callee.
3373 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003374 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003375
Chris Lattnerdf986172009-01-02 07:01:27 +00003376 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3377 // function attributes.
3378 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3379 if (FnAttrs & ObsoleteFuncAttrs) {
3380 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3381 FnAttrs &= ~ObsoleteFuncAttrs;
3382 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003383
Chris Lattnerdf986172009-01-02 07:01:27 +00003384 // Set up the Attributes for the function.
3385 SmallVector<AttributeWithIndex, 8> Attrs;
3386 if (RetAttrs != Attribute::None)
3387 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003388
Chris Lattnerdf986172009-01-02 07:01:27 +00003389 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003390
Chris Lattnerdf986172009-01-02 07:01:27 +00003391 // Loop through FunctionType's arguments and ensure they are specified
3392 // correctly. Also, gather any parameter attributes.
3393 FunctionType::param_iterator I = Ty->param_begin();
3394 FunctionType::param_iterator E = Ty->param_end();
3395 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3396 const Type *ExpectedTy = 0;
3397 if (I != E) {
3398 ExpectedTy = *I++;
3399 } else if (!Ty->isVarArg()) {
3400 return Error(ArgList[i].Loc, "too many arguments specified");
3401 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003402
Chris Lattnerdf986172009-01-02 07:01:27 +00003403 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3404 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3405 ExpectedTy->getDescription() + "'");
3406 Args.push_back(ArgList[i].V);
3407 if (ArgList[i].Attrs != Attribute::None)
3408 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3409 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003410
Chris Lattnerdf986172009-01-02 07:01:27 +00003411 if (I != E)
3412 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003413
Chris Lattnerdf986172009-01-02 07:01:27 +00003414 if (FnAttrs != Attribute::None)
3415 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003416
Chris Lattnerdf986172009-01-02 07:01:27 +00003417 // Finish off the Attributes and check them
3418 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003419
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003420 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003421 Args.begin(), Args.end());
3422 II->setCallingConv(CC);
3423 II->setAttributes(PAL);
3424 Inst = II;
3425 return false;
3426}
3427
3428
3429
3430//===----------------------------------------------------------------------===//
3431// Binary Operators.
3432//===----------------------------------------------------------------------===//
3433
3434/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003435/// ::= ArithmeticOps TypeAndValue ',' Value
3436///
3437/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3438/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003439bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003440 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003441 LocTy Loc; Value *LHS, *RHS;
3442 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3443 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3444 ParseValue(LHS->getType(), RHS, PFS))
3445 return true;
3446
Chris Lattnere914b592009-01-05 08:24:46 +00003447 bool Valid;
3448 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003449 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003450 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003451 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3452 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003453 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003454 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3455 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003456 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003457
Chris Lattnere914b592009-01-05 08:24:46 +00003458 if (!Valid)
3459 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003460
Chris Lattnerdf986172009-01-02 07:01:27 +00003461 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3462 return false;
3463}
3464
3465/// ParseLogical
3466/// ::= ArithmeticOps TypeAndValue ',' Value {
3467bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3468 unsigned Opc) {
3469 LocTy Loc; Value *LHS, *RHS;
3470 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3471 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3472 ParseValue(LHS->getType(), RHS, PFS))
3473 return true;
3474
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003475 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003476 return Error(Loc,"instruction requires integer or integer vector operands");
3477
3478 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3479 return false;
3480}
3481
3482
3483/// ParseCompare
3484/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3485/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003486bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3487 unsigned Opc) {
3488 // Parse the integer/fp comparison predicate.
3489 LocTy Loc;
3490 unsigned Pred;
3491 Value *LHS, *RHS;
3492 if (ParseCmpPredicate(Pred, Opc) ||
3493 ParseTypeAndValue(LHS, Loc, PFS) ||
3494 ParseToken(lltok::comma, "expected ',' after compare value") ||
3495 ParseValue(LHS->getType(), RHS, PFS))
3496 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003497
Chris Lattnerdf986172009-01-02 07:01:27 +00003498 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003499 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003500 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003501 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003502 } else {
3503 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003504 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003505 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003506 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003507 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003508 }
3509 return false;
3510}
3511
3512//===----------------------------------------------------------------------===//
3513// Other Instructions.
3514//===----------------------------------------------------------------------===//
3515
3516
3517/// ParseCast
3518/// ::= CastOpc TypeAndValue 'to' Type
3519bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3520 unsigned Opc) {
3521 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003522 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003523 if (ParseTypeAndValue(Op, Loc, PFS) ||
3524 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3525 ParseType(DestTy))
3526 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003527
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003528 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3529 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003530 return Error(Loc, "invalid cast opcode for cast from '" +
3531 Op->getType()->getDescription() + "' to '" +
3532 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003533 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003534 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3535 return false;
3536}
3537
3538/// ParseSelect
3539/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3540bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3541 LocTy Loc;
3542 Value *Op0, *Op1, *Op2;
3543 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3544 ParseToken(lltok::comma, "expected ',' after select condition") ||
3545 ParseTypeAndValue(Op1, PFS) ||
3546 ParseToken(lltok::comma, "expected ',' after select value") ||
3547 ParseTypeAndValue(Op2, PFS))
3548 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003549
Chris Lattnerdf986172009-01-02 07:01:27 +00003550 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3551 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003552
Chris Lattnerdf986172009-01-02 07:01:27 +00003553 Inst = SelectInst::Create(Op0, Op1, Op2);
3554 return false;
3555}
3556
Chris Lattner0088a5c2009-01-05 08:18:44 +00003557/// ParseVA_Arg
3558/// ::= 'va_arg' TypeAndValue ',' Type
3559bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003560 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003561 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003562 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003563 if (ParseTypeAndValue(Op, PFS) ||
3564 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003565 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003566 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003567
Chris Lattner0088a5c2009-01-05 08:18:44 +00003568 if (!EltTy->isFirstClassType())
3569 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003570
3571 Inst = new VAArgInst(Op, EltTy);
3572 return false;
3573}
3574
3575/// ParseExtractElement
3576/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3577bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3578 LocTy Loc;
3579 Value *Op0, *Op1;
3580 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3581 ParseToken(lltok::comma, "expected ',' after extract value") ||
3582 ParseTypeAndValue(Op1, PFS))
3583 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003584
Chris Lattnerdf986172009-01-02 07:01:27 +00003585 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3586 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003587
Eric Christophera3500da2009-07-25 02:28:41 +00003588 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003589 return false;
3590}
3591
3592/// ParseInsertElement
3593/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3594bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3595 LocTy Loc;
3596 Value *Op0, *Op1, *Op2;
3597 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3598 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3599 ParseTypeAndValue(Op1, PFS) ||
3600 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3601 ParseTypeAndValue(Op2, PFS))
3602 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003603
Chris Lattnerdf986172009-01-02 07:01:27 +00003604 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003605 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003606
Chris Lattnerdf986172009-01-02 07:01:27 +00003607 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3608 return false;
3609}
3610
3611/// ParseShuffleVector
3612/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3613bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3614 LocTy Loc;
3615 Value *Op0, *Op1, *Op2;
3616 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3617 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3618 ParseTypeAndValue(Op1, PFS) ||
3619 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3620 ParseTypeAndValue(Op2, PFS))
3621 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003622
Chris Lattnerdf986172009-01-02 07:01:27 +00003623 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3624 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003625
Chris Lattnerdf986172009-01-02 07:01:27 +00003626 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3627 return false;
3628}
3629
3630/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003631/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003632int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003633 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003634 Value *Op0, *Op1;
3635 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003636
Chris Lattnerdf986172009-01-02 07:01:27 +00003637 if (ParseType(Ty) ||
3638 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3639 ParseValue(Ty, Op0, PFS) ||
3640 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003641 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003642 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3643 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003644
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003645 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003646 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3647 while (1) {
3648 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003649
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003650 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003651 break;
3652
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003653 if (Lex.getKind() == lltok::MetadataVar) {
3654 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003655 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003656 }
Devang Patela43d46f2009-10-16 18:45:49 +00003657
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003658 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003659 ParseValue(Ty, Op0, PFS) ||
3660 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003661 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003662 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3663 return true;
3664 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003665
Chris Lattnerdf986172009-01-02 07:01:27 +00003666 if (!Ty->isFirstClassType())
3667 return Error(TypeLoc, "phi node must have first class type");
3668
3669 PHINode *PN = PHINode::Create(Ty);
3670 PN->reserveOperandSpace(PHIVals.size());
3671 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3672 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3673 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003674 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003675}
3676
3677/// ParseCall
3678/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3679/// ParameterList OptionalAttrs
3680bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3681 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003682 unsigned RetAttrs, FnAttrs;
3683 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003684 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003685 LocTy RetTypeLoc;
3686 ValID CalleeID;
3687 SmallVector<ParamInfo, 16> ArgList;
3688 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003689
Chris Lattnerdf986172009-01-02 07:01:27 +00003690 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3691 ParseOptionalCallingConv(CC) ||
3692 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003693 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003694 ParseValID(CalleeID) ||
3695 ParseParameterList(ArgList, PFS) ||
3696 ParseOptionalAttrs(FnAttrs, 2))
3697 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003698
Chris Lattnerdf986172009-01-02 07:01:27 +00003699 // If RetType is a non-function pointer type, then this is the short syntax
3700 // for the call, which means that RetType is just the return type. Infer the
3701 // rest of the function argument types from the arguments that are present.
3702 const PointerType *PFTy = 0;
3703 const FunctionType *Ty = 0;
3704 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3705 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3706 // Pull out the types of all of the arguments...
3707 std::vector<const Type*> ParamTypes;
3708 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3709 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003710
Chris Lattnerdf986172009-01-02 07:01:27 +00003711 if (!FunctionType::isValidReturnType(RetType))
3712 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003713
Owen Andersondebcb012009-07-29 22:17:13 +00003714 Ty = FunctionType::get(RetType, ParamTypes, false);
3715 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003716 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003717
Chris Lattnerdf986172009-01-02 07:01:27 +00003718 // Look up the callee.
3719 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003720 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003721
Chris Lattnerdf986172009-01-02 07:01:27 +00003722 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3723 // function attributes.
3724 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3725 if (FnAttrs & ObsoleteFuncAttrs) {
3726 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3727 FnAttrs &= ~ObsoleteFuncAttrs;
3728 }
3729
3730 // Set up the Attributes for the function.
3731 SmallVector<AttributeWithIndex, 8> Attrs;
3732 if (RetAttrs != Attribute::None)
3733 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003734
Chris Lattnerdf986172009-01-02 07:01:27 +00003735 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003736
Chris Lattnerdf986172009-01-02 07:01:27 +00003737 // Loop through FunctionType's arguments and ensure they are specified
3738 // correctly. Also, gather any parameter attributes.
3739 FunctionType::param_iterator I = Ty->param_begin();
3740 FunctionType::param_iterator E = Ty->param_end();
3741 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3742 const Type *ExpectedTy = 0;
3743 if (I != E) {
3744 ExpectedTy = *I++;
3745 } else if (!Ty->isVarArg()) {
3746 return Error(ArgList[i].Loc, "too many arguments specified");
3747 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003748
Chris Lattnerdf986172009-01-02 07:01:27 +00003749 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3750 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3751 ExpectedTy->getDescription() + "'");
3752 Args.push_back(ArgList[i].V);
3753 if (ArgList[i].Attrs != Attribute::None)
3754 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3755 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003756
Chris Lattnerdf986172009-01-02 07:01:27 +00003757 if (I != E)
3758 return Error(CallLoc, "not enough parameters specified for call");
3759
3760 if (FnAttrs != Attribute::None)
3761 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3762
3763 // Finish off the Attributes and check them
3764 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003765
Chris Lattnerdf986172009-01-02 07:01:27 +00003766 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3767 CI->setTailCall(isTail);
3768 CI->setCallingConv(CC);
3769 CI->setAttributes(PAL);
3770 Inst = CI;
3771 return false;
3772}
3773
3774//===----------------------------------------------------------------------===//
3775// Memory Instructions.
3776//===----------------------------------------------------------------------===//
3777
3778/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003779/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3780/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003781int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3782 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003783 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003784 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003785 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003786 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003787 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003788
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003789 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003790 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003791 if (Lex.getKind() == lltok::kw_align) {
3792 if (ParseOptionalAlignment(Alignment)) return true;
3793 } else if (Lex.getKind() == lltok::MetadataVar) {
3794 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003795 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003796 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3797 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3798 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003799 }
3800 }
3801
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003802 if (Size && !Size->getType()->isIntegerTy())
3803 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003804
Victor Hernandez68afa542009-10-21 19:11:40 +00003805 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003806 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003807 return AteExtraComma ? InstExtraComma : InstNormal;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003808 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003809
3810 // Autoupgrade old malloc instruction to malloc call.
3811 // FIXME: Remove in LLVM 3.0.
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003812 if (Size && !Size->getType()->isIntegerTy(32))
3813 return Error(SizeLoc, "element count must be i32");
Victor Hernandez68afa542009-10-21 19:11:40 +00003814 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003815 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3816 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003817 if (!MallocF)
3818 // Prototype malloc as "void *(int32)".
3819 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003820 MallocF = cast<Function>(
3821 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003822 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003823return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003824}
3825
3826/// ParseFree
3827/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003828bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3829 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003830 Value *Val; LocTy Loc;
3831 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003832 if (!Val->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003833 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003834 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003835 return false;
3836}
3837
3838/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003839/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003840int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3841 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003842 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003843 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003844 bool AteExtraComma = false;
3845 if (ParseTypeAndValue(Val, Loc, PFS) ||
3846 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3847 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003848
Duncan Sands1df98592010-02-16 11:11:14 +00003849 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003850 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3851 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003852
Chris Lattnerdf986172009-01-02 07:01:27 +00003853 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003854 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003855}
3856
3857/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003858/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003859int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3860 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003861 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003862 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003863 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003864 if (ParseTypeAndValue(Val, Loc, PFS) ||
3865 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003866 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3867 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003868 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003869
Duncan Sands1df98592010-02-16 11:11:14 +00003870 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003871 return Error(PtrLoc, "store operand must be a pointer");
3872 if (!Val->getType()->isFirstClassType())
3873 return Error(Loc, "store operand must be a first class value");
3874 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3875 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003876
Chris Lattnerdf986172009-01-02 07:01:27 +00003877 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003878 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003879}
3880
3881/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003882/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003883/// FIXME: Remove support for getresult in LLVM 3.0
3884bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3885 Value *Val; LocTy ValLoc, EltLoc;
3886 unsigned Element;
3887 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3888 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003889 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003890 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003891
Duncan Sands1df98592010-02-16 11:11:14 +00003892 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003893 return Error(ValLoc, "getresult inst requires an aggregate operand");
3894 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3895 return Error(EltLoc, "invalid getresult index for value");
3896 Inst = ExtractValueInst::Create(Val, Element);
3897 return false;
3898}
3899
3900/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003901/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003902int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003903 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003904
Dan Gohmandcb40a32009-07-29 15:58:36 +00003905 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003906
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003907 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003908
Duncan Sands1df98592010-02-16 11:11:14 +00003909 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003910 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003911
Chris Lattnerdf986172009-01-02 07:01:27 +00003912 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003913 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003914 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003915 if (Lex.getKind() == lltok::MetadataVar) {
3916 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003917 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003918 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003919 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003920 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003921 return Error(EltLoc, "getelementptr index must be an integer");
3922 Indices.push_back(Val);
3923 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003924
Chris Lattnerdf986172009-01-02 07:01:27 +00003925 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3926 Indices.begin(), Indices.end()))
3927 return Error(Loc, "invalid getelementptr indices");
3928 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003929 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003930 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003931 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003932}
3933
3934/// ParseExtractValue
3935/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003936int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003937 Value *Val; LocTy Loc;
3938 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003939 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003940 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003941 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003942 return true;
3943
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003944 if (!Val->getType()->isAggregateType())
3945 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003946
3947 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3948 Indices.end()))
3949 return Error(Loc, "invalid indices for extractvalue");
3950 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003951 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003952}
3953
3954/// ParseInsertValue
3955/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003956int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003957 Value *Val0, *Val1; LocTy Loc0, Loc1;
3958 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003959 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003960 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3961 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3962 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003963 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003964 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003965
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003966 if (!Val0->getType()->isAggregateType())
3967 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003968
Chris Lattnerdf986172009-01-02 07:01:27 +00003969 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3970 Indices.end()))
3971 return Error(Loc0, "invalid indices for insertvalue");
3972 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003973 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003974}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003975
3976//===----------------------------------------------------------------------===//
3977// Embedded metadata.
3978//===----------------------------------------------------------------------===//
3979
3980/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003981/// ::= Element (',' Element)*
3982/// Element
3983/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003984bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003985 PerFunctionState *PFS) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003986 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003987 // Null is a special case since it is typeless.
3988 if (EatIfPresent(lltok::kw_null)) {
3989 Elts.push_back(0);
3990 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003991 }
Chris Lattnera7352392009-12-30 04:42:57 +00003992
3993 Value *V = 0;
3994 PATypeHolder Ty(Type::getVoidTy(Context));
3995 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003996 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003997 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003998 return true;
3999
Nick Lewyckycb337992009-05-10 20:57:05 +00004000 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004001 } while (EatIfPresent(lltok::comma));
4002
4003 return false;
4004}