blob: d30fccaef86723f9c5c542cd8309b7b393f1fb64 [file] [log] [blame]
Chris Lattnerac161bf2009-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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth91065212014-03-05 10:34:14 +000016#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/CallingConv.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/InlineAsm.h"
21#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000022#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Module.h"
24#include "llvm/IR/Operator.h"
25#include "llvm/IR/ValueSymbolTable.h"
Torok Edwin56d06592009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000027#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000028#include "llvm/Support/raw_ostream.h"
29using namespace llvm;
30
Chris Lattner229907c2011-07-18 04:54:35 +000031static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000032 std::string Result;
33 raw_string_ostream Tmp(Result);
34 Tmp << *T;
35 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000036}
37
Chris Lattner3822f632009-01-02 08:05:26 +000038/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000039bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000040 // Prime the lexer.
41 Lex.Lex();
42
Chris Lattnerad6f3352009-01-04 20:44:11 +000043 return ParseTopLevelEntities() ||
44 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000045}
46
47/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48/// module.
49bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000050 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
51 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
52
Bill Wendlingb32b0412013-02-08 06:32:06 +000053 // Handle any function attribute group forward references.
54 for (std::map<Value*, std::vector<unsigned> >::iterator
55 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
56 I != E; ++I) {
57 Value *V = I->first;
58 std::vector<unsigned> &Vec = I->second;
59 AttrBuilder B;
60
61 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
62 VI != VE; ++VI)
63 B.merge(NumberedAttrBuilders[*VI]);
64
65 if (Function *Fn = dyn_cast<Function>(V)) {
66 AttributeSet AS = Fn->getAttributes();
67 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
68 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
69 AS.getFnAttributes());
70
71 FnAttrs.merge(B);
72
73 // If the alignment was parsed as an attribute, move to the alignment
74 // field.
75 if (FnAttrs.hasAlignmentAttr()) {
76 Fn->setAlignment(FnAttrs.getAlignment());
77 FnAttrs.removeAttribute(Attribute::Alignment);
78 }
79
80 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
81 AttributeSet::get(Context,
82 AttributeSet::FunctionIndex,
83 FnAttrs));
84 Fn->setAttributes(AS);
85 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
86 AttributeSet AS = CI->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +000090 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +000091 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
92 AttributeSet::get(Context,
93 AttributeSet::FunctionIndex,
94 FnAttrs));
95 CI->setAttributes(AS);
96 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
97 AttributeSet AS = II->getAttributes();
98 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
99 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
100 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000101 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000102 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
103 AttributeSet::get(Context,
104 AttributeSet::FunctionIndex,
105 FnAttrs));
106 II->setAttributes(AS);
107 } else {
108 llvm_unreachable("invalid object with forward attribute group reference");
109 }
110 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000111
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000112 // If there are entries in ForwardRefBlockAddresses at this point, the
113 // function was never defined.
114 if (!ForwardRefBlockAddresses.empty())
115 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
116 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000117
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000118 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
119 if (NumberedTypes[i].second.isValid())
120 return Error(NumberedTypes[i].second,
121 "use of undefined type '%" + Twine(i) + "'");
122
123 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
124 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
125 if (I->second.second.isValid())
126 return Error(I->second.second,
127 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000128
David Majnemerdad0a642014-06-27 18:19:56 +0000129 if (!ForwardRefComdats.empty())
130 return Error(ForwardRefComdats.begin()->second,
131 "use of undefined comdat '$" +
132 ForwardRefComdats.begin()->first + "'");
133
Chris Lattnerac161bf2009-01-02 07:01:27 +0000134 if (!ForwardRefVals.empty())
135 return Error(ForwardRefVals.begin()->second.second,
136 "use of undefined value '@" + ForwardRefVals.begin()->first +
137 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000138
Chris Lattnerac161bf2009-01-02 07:01:27 +0000139 if (!ForwardRefValIDs.empty())
140 return Error(ForwardRefValIDs.begin()->second.second,
141 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000142 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000143
Devang Pateld2541152009-07-08 19:23:54 +0000144 if (!ForwardRefMDNodes.empty())
145 return Error(ForwardRefMDNodes.begin()->second.second,
146 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000147 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000148
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000149 // Resolve metadata cycles.
150 for (auto &N : NumberedMetadata)
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000151 if (auto *U = cast_or_null<UniquableMDNode>(N))
152 U->resolveCycles();
Devang Pateld2541152009-07-08 19:23:54 +0000153
Chris Lattnerac161bf2009-01-02 07:01:27 +0000154 // Look for intrinsic functions and CallInst that need to be upgraded
155 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
156 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000157
Manman Ren8b4306c2013-12-02 21:29:56 +0000158 UpgradeDebugInfo(*M);
159
Chris Lattnerac161bf2009-01-02 07:01:27 +0000160 return false;
161}
162
163//===----------------------------------------------------------------------===//
164// Top-Level Entities
165//===----------------------------------------------------------------------===//
166
167bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000168 while (1) {
169 switch (Lex.getKind()) {
170 default: return TokError("expected top-level entity");
171 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000172 case lltok::kw_declare: if (ParseDeclare()) return true; break;
173 case lltok::kw_define: if (ParseDefine()) return true; break;
174 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
175 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000176 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000177 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000178 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000179 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000180 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000181 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000182 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000183 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000184
185 // The Global variable production with no name can have many different
186 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000187 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
188 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000189 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000190 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000191 case lltok::kw_internal: // OptionalLinkage
192 case lltok::kw_weak: // OptionalLinkage
193 case lltok::kw_weak_odr: // OptionalLinkage
194 case lltok::kw_linkonce: // OptionalLinkage
195 case lltok::kw_linkonce_odr: // OptionalLinkage
196 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000197 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000198 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000199 case lltok::kw_external: // OptionalLinkage
200 case lltok::kw_default: // OptionalVisibility
201 case lltok::kw_hidden: // OptionalVisibility
202 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000203 case lltok::kw_dllimport: // OptionalDLLStorageClass
204 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000205 case lltok::kw_thread_local: // OptionalThreadLocal
206 case lltok::kw_addrspace: // OptionalAddrSpace
207 case lltok::kw_constant: // GlobalType
208 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000209 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000210 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000211 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000212 bool HasLinkage;
213 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000214 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000215 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000216 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000217 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000218 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000219 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000220 return true;
221 break;
222 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000223
224 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000225 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
226 case lltok::kw_uselistorder_bb:
227 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000228 }
229 }
230}
231
232
233/// toplevelentity
234/// ::= 'module' 'asm' STRINGCONSTANT
235bool LLParser::ParseModuleAsm() {
236 assert(Lex.getKind() == lltok::kw_module);
237 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000238
239 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000240 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
241 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000242
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000243 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000244 return false;
245}
246
247/// toplevelentity
248/// ::= 'target' 'triple' '=' STRINGCONSTANT
249/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
250bool LLParser::ParseTargetDefinition() {
251 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000252 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000253 switch (Lex.Lex()) {
254 default: return TokError("unknown target property");
255 case lltok::kw_triple:
256 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000257 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
258 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000259 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000260 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000261 return false;
262 case lltok::kw_datalayout:
263 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000264 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
265 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000266 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000267 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000268 return false;
269 }
270}
271
Bill Wendling706d3d62012-11-28 08:41:48 +0000272/// toplevelentity
273/// ::= 'deplibs' '=' '[' ']'
274/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
275/// FIXME: Remove in 4.0. Currently parse, but ignore.
276bool LLParser::ParseDepLibs() {
277 assert(Lex.getKind() == lltok::kw_deplibs);
278 Lex.Lex();
279 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
280 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
281 return true;
282
283 if (EatIfPresent(lltok::rsquare))
284 return false;
285
286 do {
287 std::string Str;
288 if (ParseStringConstant(Str)) return true;
289 } while (EatIfPresent(lltok::comma));
290
291 return ParseToken(lltok::rsquare, "expected ']' at end of list");
292}
293
Dan Gohman466876b2009-08-12 23:32:33 +0000294/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000295/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000296bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000297 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000298 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000299 Lex.Lex(); // eat LocalVarID;
300
301 if (ParseToken(lltok::equal, "expected '=' after name") ||
302 ParseToken(lltok::kw_type, "expected 'type' after '='"))
303 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000304
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000305 if (TypeID >= NumberedTypes.size())
306 NumberedTypes.resize(TypeID+1);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000307
Craig Topper2617dcc2014-04-15 06:32:26 +0000308 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000309 if (ParseStructDefinition(TypeLoc, "",
310 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000311
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000312 if (!isa<StructType>(Result)) {
313 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
314 if (Entry.first)
315 return Error(TypeLoc, "non-struct types may not be recursive");
316 Entry.first = Result;
317 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000318 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000319
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320 return false;
321}
322
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000323
Chris Lattnerac161bf2009-01-02 07:01:27 +0000324/// toplevelentity
325/// ::= LocalVar '=' 'type' type
326bool LLParser::ParseNamedType() {
327 std::string Name = Lex.getStrVal();
328 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000329 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000330
Chris Lattner3822f632009-01-02 08:05:26 +0000331 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000332 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000333 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000334
Craig Topper2617dcc2014-04-15 06:32:26 +0000335 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000336 if (ParseStructDefinition(NameLoc, Name,
337 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000338
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000339 if (!isa<StructType>(Result)) {
340 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
341 if (Entry.first)
342 return Error(NameLoc, "non-struct types may not be recursive");
343 Entry.first = Result;
344 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000345 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000346
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000347 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000348}
349
350
351/// toplevelentity
352/// ::= 'declare' FunctionHeader
353bool LLParser::ParseDeclare() {
354 assert(Lex.getKind() == lltok::kw_declare);
355 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000356
Chris Lattnerac161bf2009-01-02 07:01:27 +0000357 Function *F;
358 return ParseFunctionHeader(F, false);
359}
360
361/// toplevelentity
362/// ::= 'define' FunctionHeader '{' ...
363bool LLParser::ParseDefine() {
364 assert(Lex.getKind() == lltok::kw_define);
365 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000366
Chris Lattnerac161bf2009-01-02 07:01:27 +0000367 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000368 return ParseFunctionHeader(F, true) ||
369 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000370}
371
Chris Lattner3822f632009-01-02 08:05:26 +0000372/// ParseGlobalType
373/// ::= 'constant'
374/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000375bool LLParser::ParseGlobalType(bool &IsConstant) {
376 if (Lex.getKind() == lltok::kw_constant)
377 IsConstant = true;
378 else if (Lex.getKind() == lltok::kw_global)
379 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000380 else {
381 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000382 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000383 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000384 Lex.Lex();
385 return false;
386}
387
Dan Gohman466876b2009-08-12 23:32:33 +0000388/// ParseUnnamedGlobal:
389/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000390/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
391/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000392/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000393/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
394/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000395bool LLParser::ParseUnnamedGlobal() {
396 unsigned VarID = NumberedVals.size();
397 std::string Name;
398 LocTy NameLoc = Lex.getLoc();
399
400 // Handle the GlobalID form.
401 if (Lex.getKind() == lltok::GlobalID) {
402 if (Lex.getUIntVal() != VarID)
403 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000404 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000405 Lex.Lex(); // eat GlobalID;
406
407 if (ParseToken(lltok::equal, "expected '=' after name"))
408 return true;
409 }
410
411 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000412 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000413 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000414 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000415 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000416 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000417 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000418 ParseOptionalThreadLocal(TLM) ||
419 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000420 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000421
Rafael Espindola464fe022014-07-30 22:51:54 +0000422 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000423 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000424 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000425 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000426 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000427}
428
Chris Lattnerac161bf2009-01-02 07:01:27 +0000429/// ParseNamedGlobal:
430/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000431/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
432/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000433bool LLParser::ParseNamedGlobal() {
434 assert(Lex.getKind() == lltok::GlobalVar);
435 LocTy NameLoc = Lex.getLoc();
436 std::string Name = Lex.getStrVal();
437 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000438
Chris Lattnerac161bf2009-01-02 07:01:27 +0000439 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000440 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000441 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000442 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000443 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
444 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000445 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000446 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000447 ParseOptionalThreadLocal(TLM) ||
448 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000449 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000450
Rafael Espindola464fe022014-07-30 22:51:54 +0000451 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000452 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000453 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000454
455 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000456 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000457}
458
David Majnemerdad0a642014-06-27 18:19:56 +0000459bool LLParser::parseComdat() {
460 assert(Lex.getKind() == lltok::ComdatVar);
461 std::string Name = Lex.getStrVal();
462 LocTy NameLoc = Lex.getLoc();
463 Lex.Lex();
464
465 if (ParseToken(lltok::equal, "expected '=' here"))
466 return true;
467
468 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
469 return TokError("expected comdat type");
470
471 Comdat::SelectionKind SK;
472 switch (Lex.getKind()) {
473 default:
474 return TokError("unknown selection kind");
475 case lltok::kw_any:
476 SK = Comdat::Any;
477 break;
478 case lltok::kw_exactmatch:
479 SK = Comdat::ExactMatch;
480 break;
481 case lltok::kw_largest:
482 SK = Comdat::Largest;
483 break;
484 case lltok::kw_noduplicates:
485 SK = Comdat::NoDuplicates;
486 break;
487 case lltok::kw_samesize:
488 SK = Comdat::SameSize;
489 break;
490 }
491 Lex.Lex();
492
493 // See if the comdat was forward referenced, if so, use the comdat.
494 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
495 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
496 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
497 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
498
499 Comdat *C;
500 if (I != ComdatSymTab.end())
501 C = &I->second;
502 else
503 C = M->getOrInsertComdat(Name);
504 C->setSelectionKind(SK);
505
506 return false;
507}
508
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000509// MDString:
510// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000511bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000512 std::string Str;
513 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000514 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000515 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000516 return false;
517}
518
519// MDNode:
520// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000521bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000522 // !{ ..., !42, ... }
523 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000524 if (ParseUInt32(MID))
525 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000526
Chris Lattner8eff0152010-04-01 05:14:45 +0000527 // If not a forward reference, just return it now.
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000528 if (MID < NumberedMetadata.size() && NumberedMetadata[MID] != nullptr) {
529 Result = NumberedMetadata[MID];
530 return false;
531 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000532
Chris Lattner8eff0152010-04-01 05:14:45 +0000533 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000534 MDNodeFwdDecl *FwdNode = MDNode::getTemporary(Context, None);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000535 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000536
Chris Lattnerfc58af22009-12-30 04:51:58 +0000537 if (NumberedMetadata.size() <= MID)
538 NumberedMetadata.resize(MID+1);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000539 NumberedMetadata[MID].reset(FwdNode);
Chris Lattner1797fc72009-12-29 21:53:55 +0000540 Result = FwdNode;
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000541 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000542}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000543
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000544/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000545/// !foo = !{ !1, !2 }
546bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000547 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000548 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000549 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000550
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000551 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000552 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000553 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000554 return true;
555
Dan Gohman2637cc12010-07-21 23:38:33 +0000556 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000557 if (Lex.getKind() != lltok::rbrace)
558 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000559 if (ParseToken(lltok::exclaim, "Expected '!' here"))
560 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000561
Craig Topper2617dcc2014-04-15 06:32:26 +0000562 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000563 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000564 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000565 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000566
567 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
568 return true;
569
Devang Patelbe626972009-07-29 00:34:02 +0000570 return false;
571}
572
Devang Patel39e64d42009-07-01 19:21:12 +0000573/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000574/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000575bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000576 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000577 Lex.Lex();
578 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000579
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000580 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000581 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000582 ParseToken(lltok::equal, "expected '=' here"))
583 return true;
584
585 // Detect common error, from old metadata syntax.
586 if (Lex.getKind() == lltok::Type)
587 return TokError("unexpected type in metadata definition");
588
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000589 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000590 if (ParseToken(lltok::exclaim, "Expected '!' here") ||
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +0000591 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000592 return true;
593
Chris Lattnerfc58af22009-12-30 04:51:58 +0000594 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000595 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000596 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000597 auto *Temp = FI->second.first;
Dan Gohman16a5d982010-08-20 22:02:26 +0000598 Temp->replaceAllUsesWith(Init);
599 MDNode::deleteTemporary(Temp);
Devang Pateld2541152009-07-08 19:23:54 +0000600 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000601
Chris Lattnerfc58af22009-12-30 04:51:58 +0000602 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
603 } else {
604 if (MetadataID >= NumberedMetadata.size())
605 NumberedMetadata.resize(MetadataID+1);
606
Craig Topper2617dcc2014-04-15 06:32:26 +0000607 if (NumberedMetadata[MetadataID] != nullptr)
Chris Lattnerfc58af22009-12-30 04:51:58 +0000608 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000609 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000610 }
611
Devang Patel39e64d42009-07-01 19:21:12 +0000612 return false;
613}
614
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000615static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
616 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
617 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
618}
619
Chris Lattnerac161bf2009-01-02 07:01:27 +0000620/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000621/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
622/// OptionalDLLStorageClass OptionalThreadLocal
623/// OptionalUnNammedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000624///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000625/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000626/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000627///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000628/// Everything through OptionalUnNammedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000629///
Rafael Espindola464fe022014-07-30 22:51:54 +0000630bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000631 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000632 GlobalVariable::ThreadLocalMode TLM,
633 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000634 assert(Lex.getKind() == lltok::kw_alias);
635 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000636
Rafael Espindola78527052013-10-06 15:10:43 +0000637 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
638
Rafael Espindolacaa43562013-10-09 16:07:32 +0000639 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000640 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000641
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000642 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000643 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000644 "symbol with local linkage must have default visibility");
645
Rafael Espindola64c1e182014-06-03 02:41:57 +0000646 Constant *Aliasee;
647 LocTy AliaseeLoc = Lex.getLoc();
648 if (Lex.getKind() != lltok::kw_bitcast &&
649 Lex.getKind() != lltok::kw_getelementptr &&
650 Lex.getKind() != lltok::kw_addrspacecast &&
651 Lex.getKind() != lltok::kw_inttoptr) {
652 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000653 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000654 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000655 // The bitcast dest type is not present, it is implied by the dest type.
656 ValID ID;
657 if (ParseValID(ID))
658 return true;
659 if (ID.Kind != ValID::t_Constant)
660 return Error(AliaseeLoc, "invalid aliasee");
661 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000662 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000663
Rafael Espindola64c1e182014-06-03 02:41:57 +0000664 Type *AliaseeType = Aliasee->getType();
665 auto *PTy = dyn_cast<PointerType>(AliaseeType);
666 if (!PTy)
667 return Error(AliaseeLoc, "An alias must have pointer type");
668 Type *Ty = PTy->getElementType();
669 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000670
671 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000672 std::unique_ptr<GlobalAlias> GA(
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +0000673 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
674 Name, Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000675 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000676 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000677 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000678 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000679
Chris Lattnerac161bf2009-01-02 07:01:27 +0000680 // See if this value already exists in the symbol table. If so, it is either
681 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000682 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000683 // See if this was a redefinition. If so, there is no entry in
684 // ForwardRefVals.
685 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
686 I = ForwardRefVals.find(Name);
687 if (I == ForwardRefVals.end())
688 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
689
690 // Otherwise, this was a definition of forward ref. Verify that types
691 // agree.
692 if (Val->getType() != GA->getType())
693 return Error(NameLoc,
694 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000695
Chris Lattnerac161bf2009-01-02 07:01:27 +0000696 // If they agree, just RAUW the old value with the alias and remove the
697 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000698 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000699 Val->eraseFromParent();
700 ForwardRefVals.erase(I);
701 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000702
Chris Lattnerac161bf2009-01-02 07:01:27 +0000703 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000704 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000705 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000706
Rafael Espindolaaa273822014-05-09 21:49:17 +0000707 // The module owns this now
708 GA.release();
709
Chris Lattnerac161bf2009-01-02 07:01:27 +0000710 return false;
711}
712
713/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000714/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000715/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000716/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000717/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000718/// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000719/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000720///
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000721/// Everything up to and including OptionalUnNammedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000722/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000723///
724bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
725 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000726 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000727 GlobalVariable::ThreadLocalMode TLM,
728 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000729 if (!isValidVisibilityForLinkage(Visibility, Linkage))
730 return Error(NameLoc,
731 "symbol with local linkage must have default visibility");
732
Chris Lattnerac161bf2009-01-02 07:01:27 +0000733 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000734 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000735 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000736 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000737
Craig Topper2617dcc2014-04-15 06:32:26 +0000738 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000739 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000740 ParseOptionalToken(lltok::kw_externally_initialized,
741 IsExternallyInitialized,
742 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000743 ParseGlobalType(IsConstant) ||
744 ParseType(Ty, TyLoc))
745 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000746
Chris Lattnerac161bf2009-01-02 07:01:27 +0000747 // If the linkage is specified and is external, then no initializer is
748 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000749 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000750 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000751 Linkage != GlobalValue::ExternalLinkage)) {
752 if (ParseGlobalValue(Ty, Init))
753 return true;
754 }
755
Duncan Sands19d0b472010-02-16 11:11:14 +0000756 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000757 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000758
David Majnemer598bd052014-12-09 05:56:09 +0000759 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000760
761 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000762 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000763 GVal = M->getNamedValue(Name);
764 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000765 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
766 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000767 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000768 } else {
769 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
770 I = ForwardRefValIDs.find(NumberedVals.size());
771 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000772 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000773 ForwardRefValIDs.erase(I);
774 }
775 }
776
David Majnemer598bd052014-12-09 05:56:09 +0000777 GlobalVariable *GV;
778 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000779 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
780 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000781 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000782 } else {
David Majnemer598bd052014-12-09 05:56:09 +0000783 if (GVal->getType()->getElementType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000784 return Error(TyLoc,
785 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000786
David Majnemer598bd052014-12-09 05:56:09 +0000787 GV = cast<GlobalVariable>(GVal);
788
Chris Lattnerac161bf2009-01-02 07:01:27 +0000789 // Move the forward-reference to the correct spot in the module.
790 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
791 }
792
793 if (Name.empty())
794 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000795
Chris Lattnerac161bf2009-01-02 07:01:27 +0000796 // Set the parsed properties on the global.
797 if (Init)
798 GV->setInitializer(Init);
799 GV->setConstant(IsConstant);
800 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
801 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000802 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000803 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000804 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000805 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000806
Chris Lattnerac161bf2009-01-02 07:01:27 +0000807 // Parse attributes on the global.
808 while (Lex.getKind() == lltok::comma) {
809 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000810
Chris Lattnerac161bf2009-01-02 07:01:27 +0000811 if (Lex.getKind() == lltok::kw_section) {
812 Lex.Lex();
813 GV->setSection(Lex.getStrVal());
814 if (ParseToken(lltok::StringConstant, "expected global section string"))
815 return true;
816 } else if (Lex.getKind() == lltok::kw_align) {
817 unsigned Alignment;
818 if (ParseOptionalAlignment(Alignment)) return true;
819 GV->setAlignment(Alignment);
820 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000821 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000822 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000823 return true;
824 if (C)
825 GV->setComdat(C);
826 else
827 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000828 }
829 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000830
Chris Lattnerac161bf2009-01-02 07:01:27 +0000831 return false;
832}
833
Bill Wendling63b88192013-02-06 06:52:58 +0000834/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000835/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000836bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000837 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000838 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000839 Lex.Lex();
840
David Majnemerb39e22b2014-12-09 18:33:57 +0000841 if (Lex.getKind() != lltok::AttrGrpID)
842 return TokError("expected attribute group id");
843
Bill Wendling63b88192013-02-06 06:52:58 +0000844 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000845 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000846 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000847 Lex.Lex();
848
849 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000850 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000851 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000852 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000853 ParseToken(lltok::rbrace, "expected end of attribute group"))
854 return true;
855
Bill Wendlingb32b0412013-02-08 06:32:06 +0000856 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000857 return Error(AttrGrpLoc, "attribute group has no attributes");
858
859 return false;
860}
861
Bill Wendling8b0321d2013-02-08 00:52:31 +0000862/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000863/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000864bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
865 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000866 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000867 bool HaveError = false;
868
869 B.clear();
870
Bill Wendling63b88192013-02-06 06:52:58 +0000871 while (true) {
872 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000873 if (Token == lltok::kw_builtin)
874 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000875 switch (Token) {
876 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000877 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000878 return Error(Lex.getLoc(), "unterminated attribute group");
879 case lltok::rbrace:
880 // Finished.
881 return false;
882
Bill Wendlingb32b0412013-02-08 06:32:06 +0000883 case lltok::AttrGrpID: {
884 // Allow a function to reference an attribute group:
885 //
886 // define void @foo() #1 { ... }
887 if (inAttrGrp)
888 HaveError |=
889 Error(Lex.getLoc(),
890 "cannot have an attribute group reference in an attribute group");
891
892 unsigned AttrGrpNum = Lex.getUIntVal();
893 if (inAttrGrp) break;
894
895 // Save the reference to the attribute group. We'll fill it in later.
896 FwdRefAttrGrps.push_back(AttrGrpNum);
897 break;
898 }
Bill Wendling63b88192013-02-06 06:52:58 +0000899 // Target-dependent attributes:
900 case lltok::StringConstant: {
901 std::string Attr = Lex.getStrVal();
902 Lex.Lex();
903 std::string Val;
904 if (EatIfPresent(lltok::equal) &&
905 ParseStringConstant(Val))
906 return true;
907
908 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000909 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000910 }
911
912 // Target-independent attributes:
913 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000914 // As a hack, we allow function alignment to be initially parsed as an
915 // attribute on a function declaration/definition or added to an attribute
916 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000917 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000918 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000919 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000920 if (ParseToken(lltok::equal, "expected '=' here") ||
921 ParseUInt32(Alignment))
922 return true;
923 } else {
924 if (ParseOptionalAlignment(Alignment))
925 return true;
926 }
Bill Wendling63b88192013-02-06 06:52:58 +0000927 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000928 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000929 }
930 case lltok::kw_alignstack: {
931 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000932 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000933 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000934 if (ParseToken(lltok::equal, "expected '=' here") ||
935 ParseUInt32(Alignment))
936 return true;
937 } else {
938 if (ParseOptionalStackAlignment(Alignment))
939 return true;
940 }
Bill Wendling63b88192013-02-06 06:52:58 +0000941 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000942 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000943 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000944 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000945 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000946 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000947 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000948 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000949 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
950 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
951 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
952 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
953 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
954 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
955 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
956 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
957 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
958 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000959 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000960 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
961 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
962 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
963 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
964 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
965 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
966 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
967 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
968 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
969 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
970 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000971
972 // Error handling.
973 case lltok::kw_inreg:
974 case lltok::kw_signext:
975 case lltok::kw_zeroext:
976 HaveError |=
977 Error(Lex.getLoc(),
978 "invalid use of attribute on a function");
979 break;
980 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +0000981 case lltok::kw_dereferenceable:
Reid Klecknera534a382013-12-19 02:14:12 +0000982 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000983 case lltok::kw_nest:
984 case lltok::kw_noalias:
985 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000986 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +0000987 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000988 case lltok::kw_sret:
989 HaveError |=
990 Error(Lex.getLoc(),
991 "invalid use of parameter-only attribute on a function");
992 break;
Bill Wendling63b88192013-02-06 06:52:58 +0000993 }
994
995 Lex.Lex();
996 }
997}
Chris Lattnerac161bf2009-01-02 07:01:27 +0000998
999//===----------------------------------------------------------------------===//
1000// GlobalValue Reference/Resolution Routines.
1001//===----------------------------------------------------------------------===//
1002
1003/// GetGlobalVal - Get a value with the specified name or ID, creating a
1004/// forward reference record if needed. This can return null if the value
1005/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001006GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001007 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001008 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001009 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001010 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001011 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001012 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001013
Chris Lattnerac161bf2009-01-02 07:01:27 +00001014 // Look this name up in the normal function symbol table.
1015 GlobalValue *Val =
1016 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001017
Chris Lattnerac161bf2009-01-02 07:01:27 +00001018 // If this is a forward reference for the value, see if we already created a
1019 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001020 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001021 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1022 I = ForwardRefVals.find(Name);
1023 if (I != ForwardRefVals.end())
1024 Val = I->second.first;
1025 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001026
Chris Lattnerac161bf2009-01-02 07:01:27 +00001027 // If we have the value in the symbol table or fwd-ref table, return it.
1028 if (Val) {
1029 if (Val->getType() == Ty) return Val;
1030 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001031 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001032 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001033 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001034
Chris Lattnerac161bf2009-01-02 07:01:27 +00001035 // Otherwise, create a new forward reference for this value and remember it.
1036 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001037 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001038 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001039 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001040 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001041 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1042 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001043 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001044
Chris Lattnerac161bf2009-01-02 07:01:27 +00001045 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1046 return FwdVal;
1047}
1048
Chris Lattner229907c2011-07-18 04:54:35 +00001049GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1050 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001051 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001052 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001053 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001054 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001055
Craig Topper2617dcc2014-04-15 06:32:26 +00001056 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001057
Chris Lattnerac161bf2009-01-02 07:01:27 +00001058 // If this is a forward reference for the value, see if we already created a
1059 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001060 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001061 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1062 I = ForwardRefValIDs.find(ID);
1063 if (I != ForwardRefValIDs.end())
1064 Val = I->second.first;
1065 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001066
Chris Lattnerac161bf2009-01-02 07:01:27 +00001067 // If we have the value in the symbol table or fwd-ref table, return it.
1068 if (Val) {
1069 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001070 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001071 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001072 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001073 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001074
Chris Lattnerac161bf2009-01-02 07:01:27 +00001075 // Otherwise, create a new forward reference for this value and remember it.
1076 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001077 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001078 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001079 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001080 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001081 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001082
Chris Lattnerac161bf2009-01-02 07:01:27 +00001083 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1084 return FwdVal;
1085}
1086
1087
1088//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001089// Comdat Reference/Resolution Routines.
1090//===----------------------------------------------------------------------===//
1091
1092Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1093 // Look this name up in the comdat symbol table.
1094 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1095 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1096 if (I != ComdatSymTab.end())
1097 return &I->second;
1098
1099 // Otherwise, create a new forward reference for this value and remember it.
1100 Comdat *C = M->getOrInsertComdat(Name);
1101 ForwardRefComdats[Name] = Loc;
1102 return C;
1103}
1104
1105
1106//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001107// Helper Routines.
1108//===----------------------------------------------------------------------===//
1109
1110/// ParseToken - If the current token has the specified kind, eat it and return
1111/// success. Otherwise, emit the specified error and return failure.
1112bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1113 if (Lex.getKind() != T)
1114 return TokError(ErrMsg);
1115 Lex.Lex();
1116 return false;
1117}
1118
Chris Lattner3822f632009-01-02 08:05:26 +00001119/// ParseStringConstant
1120/// ::= StringConstant
1121bool LLParser::ParseStringConstant(std::string &Result) {
1122 if (Lex.getKind() != lltok::StringConstant)
1123 return TokError("expected string constant");
1124 Result = Lex.getStrVal();
1125 Lex.Lex();
1126 return false;
1127}
1128
1129/// ParseUInt32
1130/// ::= uint32
1131bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001132 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1133 return TokError("expected integer");
1134 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1135 if (Val64 != unsigned(Val64))
1136 return TokError("expected 32-bit integer (too large)");
1137 Val = Val64;
1138 Lex.Lex();
1139 return false;
1140}
1141
Hal Finkelb0407ba2014-07-18 15:51:28 +00001142/// ParseUInt64
1143/// ::= uint64
1144bool LLParser::ParseUInt64(uint64_t &Val) {
1145 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1146 return TokError("expected integer");
1147 Val = Lex.getAPSIntVal().getLimitedValue();
1148 Lex.Lex();
1149 return false;
1150}
1151
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001152/// ParseTLSModel
1153/// := 'localdynamic'
1154/// := 'initialexec'
1155/// := 'localexec'
1156bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1157 switch (Lex.getKind()) {
1158 default:
1159 return TokError("expected localdynamic, initialexec or localexec");
1160 case lltok::kw_localdynamic:
1161 TLM = GlobalVariable::LocalDynamicTLSModel;
1162 break;
1163 case lltok::kw_initialexec:
1164 TLM = GlobalVariable::InitialExecTLSModel;
1165 break;
1166 case lltok::kw_localexec:
1167 TLM = GlobalVariable::LocalExecTLSModel;
1168 break;
1169 }
1170
1171 Lex.Lex();
1172 return false;
1173}
1174
1175/// ParseOptionalThreadLocal
1176/// := /*empty*/
1177/// := 'thread_local'
1178/// := 'thread_local' '(' tlsmodel ')'
1179bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1180 TLM = GlobalVariable::NotThreadLocal;
1181 if (!EatIfPresent(lltok::kw_thread_local))
1182 return false;
1183
1184 TLM = GlobalVariable::GeneralDynamicTLSModel;
1185 if (Lex.getKind() == lltok::lparen) {
1186 Lex.Lex();
1187 return ParseTLSModel(TLM) ||
1188 ParseToken(lltok::rparen, "expected ')' after thread local model");
1189 }
1190 return false;
1191}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001192
1193/// ParseOptionalAddrSpace
1194/// := /*empty*/
1195/// := 'addrspace' '(' uint32 ')'
1196bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1197 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001198 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001199 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001200 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001201 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001202 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001203}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001204
Bill Wendling34c2eb22012-12-04 23:40:58 +00001205/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1206bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1207 bool HaveError = false;
1208
1209 B.clear();
1210
1211 while (1) {
1212 lltok::Kind Token = Lex.getKind();
1213 switch (Token) {
1214 default: // End of attributes.
1215 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001216 case lltok::kw_align: {
1217 unsigned Alignment;
1218 if (ParseOptionalAlignment(Alignment))
1219 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001220 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001221 continue;
1222 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001223 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001224 case lltok::kw_dereferenceable: {
1225 uint64_t Bytes;
1226 if (ParseOptionalDereferenceableBytes(Bytes))
1227 return true;
1228 B.addDereferenceableAttr(Bytes);
1229 continue;
1230 }
Reid Klecknera534a382013-12-19 02:14:12 +00001231 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001232 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1233 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1234 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1235 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001236 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001237 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1238 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001239 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001240 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1241 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1242 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001243
Stephen Lin7577ed52013-04-20 13:16:13 +00001244 case lltok::kw_alignstack:
1245 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001246 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001247 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001248 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001249 case lltok::kw_minsize:
1250 case lltok::kw_naked:
1251 case lltok::kw_nobuiltin:
1252 case lltok::kw_noduplicate:
1253 case lltok::kw_noimplicitfloat:
1254 case lltok::kw_noinline:
1255 case lltok::kw_nonlazybind:
1256 case lltok::kw_noredzone:
1257 case lltok::kw_noreturn:
1258 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001259 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001260 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001261 case lltok::kw_returns_twice:
1262 case lltok::kw_sanitize_address:
1263 case lltok::kw_sanitize_memory:
1264 case lltok::kw_sanitize_thread:
1265 case lltok::kw_ssp:
1266 case lltok::kw_sspreq:
1267 case lltok::kw_sspstrong:
1268 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001269 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1270 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001271 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001272
Bill Wendling34c2eb22012-12-04 23:40:58 +00001273 Lex.Lex();
1274 }
1275}
1276
1277/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1278bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1279 bool HaveError = false;
1280
1281 B.clear();
1282
1283 while (1) {
1284 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001285 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001286 default: // End of attributes.
1287 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001288 case lltok::kw_dereferenceable: {
1289 uint64_t Bytes;
1290 if (ParseOptionalDereferenceableBytes(Bytes))
1291 return true;
1292 B.addDereferenceableAttr(Bytes);
1293 continue;
1294 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001295 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1296 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001297 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001298 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1299 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001300
Bill Wendling34c2eb22012-12-04 23:40:58 +00001301 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001302 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001303 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001304 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001305 case lltok::kw_nest:
1306 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001307 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001308 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001309 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001310 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001311
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001312 case lltok::kw_alignstack:
1313 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001314 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001315 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001316 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001317 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001318 case lltok::kw_minsize:
1319 case lltok::kw_naked:
1320 case lltok::kw_nobuiltin:
1321 case lltok::kw_noduplicate:
1322 case lltok::kw_noimplicitfloat:
1323 case lltok::kw_noinline:
1324 case lltok::kw_nonlazybind:
1325 case lltok::kw_noredzone:
1326 case lltok::kw_noreturn:
1327 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001328 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001329 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001330 case lltok::kw_returns_twice:
1331 case lltok::kw_sanitize_address:
1332 case lltok::kw_sanitize_memory:
1333 case lltok::kw_sanitize_thread:
1334 case lltok::kw_ssp:
1335 case lltok::kw_sspreq:
1336 case lltok::kw_sspstrong:
1337 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001338 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001339 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001340
1341 case lltok::kw_readnone:
1342 case lltok::kw_readonly:
1343 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001344 }
1345
Chris Lattnerac161bf2009-01-02 07:01:27 +00001346 Lex.Lex();
1347 }
1348}
1349
1350/// ParseOptionalLinkage
1351/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001352/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001353/// ::= 'internal'
1354/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001355/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001356/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001357/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001358/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001359/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001360/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001361/// ::= 'extern_weak'
1362/// ::= 'external'
1363bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1364 HasLinkage = false;
1365 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001366 default: Res=GlobalValue::ExternalLinkage; return false;
1367 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001368 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1369 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1370 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1371 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1372 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001373 case lltok::kw_available_externally:
1374 Res = GlobalValue::AvailableExternallyLinkage;
1375 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001376 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001377 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001378 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1379 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001380 }
1381 Lex.Lex();
1382 HasLinkage = true;
1383 return false;
1384}
1385
1386/// ParseOptionalVisibility
1387/// ::= /*empty*/
1388/// ::= 'default'
1389/// ::= 'hidden'
1390/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001391///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001392bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1393 switch (Lex.getKind()) {
1394 default: Res = GlobalValue::DefaultVisibility; return false;
1395 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1396 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1397 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1398 }
1399 Lex.Lex();
1400 return false;
1401}
1402
Nico Rieck7157bb72014-01-14 15:22:47 +00001403/// ParseOptionalDLLStorageClass
1404/// ::= /*empty*/
1405/// ::= 'dllimport'
1406/// ::= 'dllexport'
1407///
1408bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1409 switch (Lex.getKind()) {
1410 default: Res = GlobalValue::DefaultStorageClass; return false;
1411 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1412 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1413 }
1414 Lex.Lex();
1415 return false;
1416}
1417
Chris Lattnerac161bf2009-01-02 07:01:27 +00001418/// ParseOptionalCallingConv
1419/// ::= /*empty*/
1420/// ::= 'ccc'
1421/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001422/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001423/// ::= 'coldcc'
1424/// ::= 'x86_stdcallcc'
1425/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001426/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001427/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001428/// ::= 'arm_apcscc'
1429/// ::= 'arm_aapcscc'
1430/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001431/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001432/// ::= 'ptx_kernel'
1433/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001434/// ::= 'spir_func'
1435/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001436/// ::= 'x86_64_sysvcc'
1437/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001438/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001439/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001440/// ::= 'preserve_mostcc'
1441/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001442/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001443/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001444///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001445bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001446 switch (Lex.getKind()) {
1447 default: CC = CallingConv::C; return false;
1448 case lltok::kw_ccc: CC = CallingConv::C; break;
1449 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1450 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1451 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1452 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001453 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001454 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001455 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1456 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1457 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001458 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001459 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1460 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001461 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1462 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001463 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001464 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1465 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001466 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001467 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001468 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1469 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001470 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001471 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001472 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001473 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001474 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001475 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001476
Chris Lattnerac161bf2009-01-02 07:01:27 +00001477 Lex.Lex();
1478 return false;
1479}
1480
Chris Lattner5c427632009-12-30 05:31:19 +00001481/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001482/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman338d9a42010-08-24 02:05:17 +00001483bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1484 PerFunctionState *PFS) {
Chris Lattner5c427632009-12-30 05:31:19 +00001485 do {
1486 if (Lex.getKind() != lltok::MetadataVar)
1487 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001488
Chris Lattner596760d2009-12-29 21:25:40 +00001489 std::string Name = Lex.getStrVal();
Benjamin Kramerb3bd0192011-12-06 11:50:26 +00001490 unsigned MDK = M->getMDKindID(Name);
Chris Lattner596760d2009-12-29 21:25:40 +00001491 Lex.Lex();
Chris Lattner8d58f2f2009-10-19 05:31:10 +00001492
Dan Gohmanc828c542010-08-24 02:24:03 +00001493 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001494 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001495
Duncan P. N. Exon Smithab617d52015-01-12 21:13:09 +00001496 // This code is similar to that of ParseMetadata. However, only MDNodes
1497 // are supported here.
Dan Gohmanc828c542010-08-24 02:24:03 +00001498 if (Lex.getKind() == lltok::lbrace) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001499 MDNode *N;
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00001500 if (ParseMDTuple(N))
Dan Gohmanc828c542010-08-24 02:24:03 +00001501 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001502 Inst->setMetadata(MDK, N);
Chris Lattner8eff0152010-04-01 05:14:45 +00001503 } else {
Duncan P. N. Exon Smithab617d52015-01-12 21:13:09 +00001504 MDNode *Node;
1505 if (ParseMDNodeID(Node))
Dan Gohmanc828c542010-08-24 02:24:03 +00001506 return true;
Duncan P. N. Exon Smithab617d52015-01-12 21:13:09 +00001507 // If we got the node, add it to the instruction.
1508 Inst->setMetadata(MDK, Node);
Chris Lattner8eff0152010-04-01 05:14:45 +00001509 }
Chris Lattner596760d2009-12-29 21:25:40 +00001510
Manman Ren209b17c2013-09-28 00:22:27 +00001511 if (MDK == LLVMContext::MD_tbaa)
1512 InstsWithTBAATag.push_back(Inst);
1513
Chris Lattner596760d2009-12-29 21:25:40 +00001514 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001515 } while (EatIfPresent(lltok::comma));
1516 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001517}
1518
Chris Lattnerac161bf2009-01-02 07:01:27 +00001519/// ParseOptionalAlignment
1520/// ::= /* empty */
1521/// ::= 'align' 4
1522bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1523 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001524 if (!EatIfPresent(lltok::kw_align))
1525 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001526 LocTy AlignLoc = Lex.getLoc();
1527 if (ParseUInt32(Alignment)) return true;
1528 if (!isPowerOf2_32(Alignment))
1529 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001530 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001531 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001532 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001533}
1534
Hal Finkelb0407ba2014-07-18 15:51:28 +00001535/// ParseOptionalDereferenceableBytes
1536/// ::= /* empty */
1537/// ::= 'dereferenceable' '(' 4 ')'
1538bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1539 Bytes = 0;
1540 if (!EatIfPresent(lltok::kw_dereferenceable))
1541 return false;
1542 LocTy ParenLoc = Lex.getLoc();
1543 if (!EatIfPresent(lltok::lparen))
1544 return Error(ParenLoc, "expected '('");
1545 LocTy DerefLoc = Lex.getLoc();
1546 if (ParseUInt64(Bytes)) return true;
1547 ParenLoc = Lex.getLoc();
1548 if (!EatIfPresent(lltok::rparen))
1549 return Error(ParenLoc, "expected ')'");
1550 if (!Bytes)
1551 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1552 return false;
1553}
1554
Chris Lattnerb2f39502009-12-30 05:44:30 +00001555/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001556/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001557/// ::= ',' align 4
1558///
1559/// This returns with AteExtraComma set to true if it ate an excess comma at the
1560/// end.
1561bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1562 bool &AteExtraComma) {
1563 AteExtraComma = false;
1564 while (EatIfPresent(lltok::comma)) {
1565 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001566 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001567 AteExtraComma = true;
1568 return false;
1569 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001570
Chris Lattner95b0ff42010-04-23 00:50:50 +00001571 if (Lex.getKind() != lltok::kw_align)
1572 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001573
Chris Lattner95b0ff42010-04-23 00:50:50 +00001574 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001575 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001576
Devang Patelea8a4b92009-09-17 23:04:48 +00001577 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001578}
1579
Eli Friedmanfee02c62011-07-25 23:16:38 +00001580/// ParseScopeAndOrdering
1581/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1582/// else: ::=
1583///
1584/// This sets Scope and Ordering to the parsed values.
1585bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1586 AtomicOrdering &Ordering) {
1587 if (!isAtomic)
1588 return false;
1589
1590 Scope = CrossThread;
1591 if (EatIfPresent(lltok::kw_singlethread))
1592 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001593
1594 return ParseOrdering(Ordering);
1595}
1596
1597/// ParseOrdering
1598/// ::= AtomicOrdering
1599///
1600/// This sets Ordering to the parsed value.
1601bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001602 switch (Lex.getKind()) {
1603 default: return TokError("Expected ordering on atomic instruction");
1604 case lltok::kw_unordered: Ordering = Unordered; break;
1605 case lltok::kw_monotonic: Ordering = Monotonic; break;
1606 case lltok::kw_acquire: Ordering = Acquire; break;
1607 case lltok::kw_release: Ordering = Release; break;
1608 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1609 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1610 }
1611 Lex.Lex();
1612 return false;
1613}
1614
Charles Davisbe5557e2010-02-12 00:31:15 +00001615/// ParseOptionalStackAlignment
1616/// ::= /* empty */
1617/// ::= 'alignstack' '(' 4 ')'
1618bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1619 Alignment = 0;
1620 if (!EatIfPresent(lltok::kw_alignstack))
1621 return false;
1622 LocTy ParenLoc = Lex.getLoc();
1623 if (!EatIfPresent(lltok::lparen))
1624 return Error(ParenLoc, "expected '('");
1625 LocTy AlignLoc = Lex.getLoc();
1626 if (ParseUInt32(Alignment)) return true;
1627 ParenLoc = Lex.getLoc();
1628 if (!EatIfPresent(lltok::rparen))
1629 return Error(ParenLoc, "expected ')'");
1630 if (!isPowerOf2_32(Alignment))
1631 return Error(AlignLoc, "stack alignment is not a power of two");
1632 return false;
1633}
Devang Patelea8a4b92009-09-17 23:04:48 +00001634
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001635/// ParseIndexList - This parses the index list for an insert/extractvalue
1636/// instruction. This sets AteExtraComma in the case where we eat an extra
1637/// comma at the end of the line and find that it is followed by metadata.
1638/// Clients that don't allow metadata can call the version of this function that
1639/// only takes one argument.
1640///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001641/// ParseIndexList
1642/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001643///
1644bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1645 bool &AteExtraComma) {
1646 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001647
Chris Lattnerac161bf2009-01-02 07:01:27 +00001648 if (Lex.getKind() != lltok::comma)
1649 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001650
Chris Lattner3822f632009-01-02 08:05:26 +00001651 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001652 if (Lex.getKind() == lltok::MetadataVar) {
1653 AteExtraComma = true;
1654 return false;
1655 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001656 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001657 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001658 Indices.push_back(Idx);
1659 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001660
Chris Lattnerac161bf2009-01-02 07:01:27 +00001661 return false;
1662}
1663
1664//===----------------------------------------------------------------------===//
1665// Type Parsing.
1666//===----------------------------------------------------------------------===//
1667
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001668/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001669bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001670 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001671 switch (Lex.getKind()) {
1672 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001673 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001674 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001675 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001676 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001677 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001678 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001679 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001680 // Type ::= StructType
1681 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001682 return true;
1683 break;
1684 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001685 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001686 Lex.Lex(); // eat the lsquare.
1687 if (ParseArrayVectorType(Result, false))
1688 return true;
1689 break;
1690 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001691 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001692 Lex.Lex();
1693 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001694 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001695 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001696 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001697 } else if (ParseArrayVectorType(Result, true))
1698 return true;
1699 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001700 case lltok::LocalVar: {
1701 // Type ::= %foo
1702 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001703
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001704 // If the type hasn't been defined yet, create a forward definition and
1705 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001706 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001707 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001708 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001709 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001710 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001711 Lex.Lex();
1712 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001713 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001714
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001715 case lltok::LocalVarID: {
1716 // Type ::= %4
1717 if (Lex.getUIntVal() >= NumberedTypes.size())
1718 NumberedTypes.resize(Lex.getUIntVal()+1);
1719 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001720
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001721 // If the type hasn't been defined yet, create a forward definition and
1722 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001723 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001724 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001725 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001726 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001727 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001728 Lex.Lex();
1729 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001730 }
1731 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001732
1733 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001734 while (1) {
1735 switch (Lex.getKind()) {
1736 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001737 default:
1738 if (!AllowVoid && Result->isVoidTy())
1739 return Error(TypeLoc, "void type only allowed for function results");
1740 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001741
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001742 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001743 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001744 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001745 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001746 if (Result->isVoidTy())
1747 return TokError("pointers to void are invalid - use i8* instead");
1748 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001749 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001750 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001751 Lex.Lex();
1752 break;
1753
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001754 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001755 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001756 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001757 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001758 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001759 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001760 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001761 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001762 unsigned AddrSpace;
1763 if (ParseOptionalAddrSpace(AddrSpace) ||
1764 ParseToken(lltok::star, "expected '*' in address space"))
1765 return true;
1766
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001767 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001768 break;
1769 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001770
Chris Lattnerac161bf2009-01-02 07:01:27 +00001771 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1772 case lltok::lparen:
1773 if (ParseFunctionType(Result))
1774 return true;
1775 break;
1776 }
1777 }
1778}
1779
1780/// ParseParameterList
1781/// ::= '(' ')'
1782/// ::= '(' Arg (',' Arg)* ')'
1783/// Arg
1784/// ::= Type OptionalAttributes Value OptionalAttributes
1785bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001786 PerFunctionState &PFS, bool IsMustTailCall,
1787 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001788 if (ParseToken(lltok::lparen, "expected '(' in call"))
1789 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001790
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001791 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001792 while (Lex.getKind() != lltok::rparen) {
1793 // If this isn't the first argument, we need a comma.
1794 if (!ArgList.empty() &&
1795 ParseToken(lltok::comma, "expected ',' in argument list"))
1796 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001797
Reid Kleckner83498642014-08-26 00:33:28 +00001798 // Parse an ellipsis if this is a musttail call in a variadic function.
1799 if (Lex.getKind() == lltok::dotdotdot) {
1800 const char *Msg = "unexpected ellipsis in argument list for ";
1801 if (!IsMustTailCall)
1802 return TokError(Twine(Msg) + "non-musttail call");
1803 if (!InVarArgsFunc)
1804 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1805 Lex.Lex(); // Lex the '...', it is purely for readability.
1806 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1807 }
1808
Chris Lattnerac161bf2009-01-02 07:01:27 +00001809 // Parse the argument.
1810 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001811 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001812 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001813 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001814 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001815 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001816
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001817 if (ArgTy->isMetadataTy()) {
1818 if (ParseMetadataAsValue(V, PFS))
1819 return true;
1820 } else {
1821 // Otherwise, handle normal operands.
1822 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1823 return true;
1824 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001825 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1826 AttrIndex++,
1827 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001828 }
1829
Reid Kleckner83498642014-08-26 00:33:28 +00001830 if (IsMustTailCall && InVarArgsFunc)
1831 return TokError("expected '...' at end of argument list for musttail call "
1832 "in varargs function");
1833
Chris Lattnerac161bf2009-01-02 07:01:27 +00001834 Lex.Lex(); // Lex the ')'.
1835 return false;
1836}
1837
1838
1839
Chris Lattner2ed06b42009-01-05 18:34:07 +00001840/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001841/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001842/// ::= '(' ArgTypeListI ')'
1843/// ArgTypeListI
1844/// ::= /*empty*/
1845/// ::= '...'
1846/// ::= ArgTypeList ',' '...'
1847/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001848///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001849bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1850 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001851 isVarArg = false;
1852 assert(Lex.getKind() == lltok::lparen);
1853 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001854
Chris Lattnerac161bf2009-01-02 07:01:27 +00001855 if (Lex.getKind() == lltok::rparen) {
1856 // empty
1857 } else if (Lex.getKind() == lltok::dotdotdot) {
1858 isVarArg = true;
1859 Lex.Lex();
1860 } else {
1861 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001862 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001863 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001864 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001865
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001866 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001867 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001868
Chris Lattnerfdd87902009-10-05 05:54:46 +00001869 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001870 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001871
Chris Lattnerdef19492011-06-17 06:36:20 +00001872 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001873 Name = Lex.getStrVal();
1874 Lex.Lex();
1875 }
Chris Lattner3822f632009-01-02 08:05:26 +00001876
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001877 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001878 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001879
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001880 unsigned AttrIndex = 1;
Bill Wendlingd079a442012-10-15 04:46:55 +00001881 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001882 AttributeSet::get(ArgTy->getContext(),
1883 AttrIndex++, Attrs), Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001884
Chris Lattner3822f632009-01-02 08:05:26 +00001885 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001886 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001887 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001888 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001889 break;
1890 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001891
Chris Lattnerac161bf2009-01-02 07:01:27 +00001892 // Otherwise must be an argument type.
1893 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001894 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001895
Chris Lattnerfdd87902009-10-05 05:54:46 +00001896 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001897 return Error(TypeLoc, "argument can not have void type");
1898
Chris Lattnerdef19492011-06-17 06:36:20 +00001899 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001900 Name = Lex.getStrVal();
1901 Lex.Lex();
1902 } else {
1903 Name = "";
1904 }
Chris Lattner3822f632009-01-02 08:05:26 +00001905
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001906 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001907 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001908
Bill Wendlingd079a442012-10-15 04:46:55 +00001909 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001910 AttributeSet::get(ArgTy->getContext(),
1911 AttrIndex++, Attrs),
Bill Wendlingd079a442012-10-15 04:46:55 +00001912 Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001913 }
1914 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001915
Chris Lattner3822f632009-01-02 08:05:26 +00001916 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001917}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001918
Chris Lattnerac161bf2009-01-02 07:01:27 +00001919/// ParseFunctionType
1920/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001921bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001922 assert(Lex.getKind() == lltok::lparen);
1923
Chris Lattnerce473c72009-01-05 08:04:33 +00001924 if (!FunctionType::isValidReturnType(Result))
1925 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001926
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001927 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001928 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001929 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001930 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001931
Chris Lattnerac161bf2009-01-02 07:01:27 +00001932 // Reject names on the arguments lists.
1933 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1934 if (!ArgList[i].Name.empty())
1935 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001936 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001937 return Error(ArgList[i].Loc,
1938 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001939 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001940
Jay Foadb804a2b2011-07-12 14:06:48 +00001941 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001942 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001943 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001944
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001945 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001946 return false;
1947}
1948
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001949/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1950/// other structs.
1951bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1952 SmallVector<Type*, 8> Elts;
1953 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001954
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001955 Result = StructType::get(Context, Elts, Packed);
1956 return false;
1957}
1958
1959/// ParseStructDefinition - Parse a struct in a 'type' definition.
1960bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1961 std::pair<Type*, LocTy> &Entry,
1962 Type *&ResultTy) {
1963 // If the type was already defined, diagnose the redefinition.
1964 if (Entry.first && !Entry.second.isValid())
1965 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001966
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001967 // If we have opaque, just return without filling in the definition for the
1968 // struct. This counts as a definition as far as the .ll file goes.
1969 if (EatIfPresent(lltok::kw_opaque)) {
1970 // This type is being defined, so clear the location to indicate this.
1971 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001972
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001973 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00001974 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00001975 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001976 ResultTy = Entry.first;
1977 return false;
1978 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001979
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001980 // If the type starts with '<', then it is either a packed struct or a vector.
1981 bool isPacked = EatIfPresent(lltok::less);
1982
1983 // If we don't have a struct, then we have a random type alias, which we
1984 // accept for compatibility with old files. These types are not allowed to be
1985 // forward referenced and not allowed to be recursive.
1986 if (Lex.getKind() != lltok::lbrace) {
1987 if (Entry.first)
1988 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001989
Craig Topper2617dcc2014-04-15 06:32:26 +00001990 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001991 if (isPacked)
1992 return ParseArrayVectorType(ResultTy, true);
1993 return ParseType(ResultTy);
1994 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001995
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001996 // This type is being defined, so clear the location to indicate this.
1997 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001998
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001999 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002000 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002001 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002002
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002003 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002004
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002005 SmallVector<Type*, 8> Body;
2006 if (ParseStructBody(Body) ||
2007 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2008 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002009
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002010 STy->setBody(Body, isPacked);
2011 ResultTy = STy;
2012 return false;
2013}
2014
2015
Chris Lattnerac161bf2009-01-02 07:01:27 +00002016/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002017/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002018/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002019/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002020/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002021/// ::= '<' '{' Type (',' Type)* '}' '>'
2022bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002023 assert(Lex.getKind() == lltok::lbrace);
2024 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002025
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002026 // Handle the empty struct.
2027 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002028 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002029
Chris Lattnerf880ca22009-03-09 04:49:14 +00002030 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002031 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002032 if (ParseType(Ty)) return true;
2033 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002034
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002035 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002036 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002037
Chris Lattner3822f632009-01-02 08:05:26 +00002038 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002039 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002040 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002041
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002042 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002043 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002044
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002045 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002046 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002047
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002048 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002049}
2050
2051/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2052/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002053/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002054/// ::= '[' APSINTVAL 'x' Types ']'
2055/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002056bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002057 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2058 Lex.getAPSIntVal().getBitWidth() > 64)
2059 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002060
Chris Lattnerac161bf2009-01-02 07:01:27 +00002061 LocTy SizeLoc = Lex.getLoc();
2062 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002063 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002064
Chris Lattner3822f632009-01-02 08:05:26 +00002065 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2066 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002067
2068 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002069 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002070 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002071
Chris Lattner3822f632009-01-02 08:05:26 +00002072 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2073 "expected end of sequential type"))
2074 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002075
Chris Lattnerac161bf2009-01-02 07:01:27 +00002076 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002077 if (Size == 0)
2078 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002079 if ((unsigned)Size != Size)
2080 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002081 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002082 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002083 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002084 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002085 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002086 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002087 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002088 }
2089 return false;
2090}
2091
2092//===----------------------------------------------------------------------===//
2093// Function Semantic Analysis.
2094//===----------------------------------------------------------------------===//
2095
Chris Lattner3432c622009-10-28 03:39:23 +00002096LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2097 int functionNumber)
2098 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002099
2100 // Insert unnamed arguments into the NumberedVals list.
2101 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2102 AI != E; ++AI)
2103 if (!AI->hasName())
2104 NumberedVals.push_back(AI);
2105}
2106
2107LLParser::PerFunctionState::~PerFunctionState() {
2108 // If there were any forward referenced non-basicblock values, delete them.
2109 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2110 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2111 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002112 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002113 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002114 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002115 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002116 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002117
Chris Lattnerac161bf2009-01-02 07:01:27 +00002118 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2119 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2120 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002121 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002122 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002123 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002124 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125 }
2126}
2127
Chris Lattner3432c622009-10-28 03:39:23 +00002128bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002129 if (!ForwardRefVals.empty())
2130 return P.Error(ForwardRefVals.begin()->second.second,
2131 "use of undefined value '%" + ForwardRefVals.begin()->first +
2132 "'");
2133 if (!ForwardRefValIDs.empty())
2134 return P.Error(ForwardRefValIDs.begin()->second.second,
2135 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002136 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002137 return false;
2138}
2139
2140
2141/// GetVal - Get a value with the specified name or ID, creating a
2142/// forward reference record if needed. This can return null if the value
2143/// exists but does not have the right type.
2144Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002145 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002146 // Look this name up in the normal function symbol table.
2147 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002148
Chris Lattnerac161bf2009-01-02 07:01:27 +00002149 // If this is a forward reference for the value, see if we already created a
2150 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002151 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002152 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2153 I = ForwardRefVals.find(Name);
2154 if (I != ForwardRefVals.end())
2155 Val = I->second.first;
2156 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002157
Chris Lattnerac161bf2009-01-02 07:01:27 +00002158 // If we have the value in the symbol table or fwd-ref table, return it.
2159 if (Val) {
2160 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002161 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002162 P.Error(Loc, "'%" + Name + "' is not a basic block");
2163 else
2164 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002165 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002166 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002167 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002168
Chris Lattnerac161bf2009-01-02 07:01:27 +00002169 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002170 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002171 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002172 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002173 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002174
Chris Lattnerac161bf2009-01-02 07:01:27 +00002175 // Otherwise, create a new forward reference for this value and remember it.
2176 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002177 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002178 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002179 else
2180 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002181
Chris Lattnerac161bf2009-01-02 07:01:27 +00002182 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2183 return FwdVal;
2184}
2185
Chris Lattner229907c2011-07-18 04:54:35 +00002186Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002187 LocTy Loc) {
2188 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002189 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002190
Chris Lattnerac161bf2009-01-02 07:01:27 +00002191 // If this is a forward reference for the value, see if we already created a
2192 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002193 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002194 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2195 I = ForwardRefValIDs.find(ID);
2196 if (I != ForwardRefValIDs.end())
2197 Val = I->second.first;
2198 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002199
Chris Lattnerac161bf2009-01-02 07:01:27 +00002200 // If we have the value in the symbol table or fwd-ref table, return it.
2201 if (Val) {
2202 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002203 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002204 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002206 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002207 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002208 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002209 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002210
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002211 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002212 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002213 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002214 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002215
Chris Lattnerac161bf2009-01-02 07:01:27 +00002216 // Otherwise, create a new forward reference for this value and remember it.
2217 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002218 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002219 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002220 else
2221 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002222
Chris Lattnerac161bf2009-01-02 07:01:27 +00002223 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2224 return FwdVal;
2225}
2226
2227/// SetInstName - After an instruction is parsed and inserted into its
2228/// basic block, this installs its name.
2229bool LLParser::PerFunctionState::SetInstName(int NameID,
2230 const std::string &NameStr,
2231 LocTy NameLoc, Instruction *Inst) {
2232 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002233 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002234 if (NameID != -1 || !NameStr.empty())
2235 return P.Error(NameLoc, "instructions returning void cannot have a name");
2236 return false;
2237 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002238
Chris Lattnerac161bf2009-01-02 07:01:27 +00002239 // If this was a numbered instruction, verify that the instruction is the
2240 // expected value and resolve any forward references.
2241 if (NameStr.empty()) {
2242 // If neither a name nor an ID was specified, just use the next ID.
2243 if (NameID == -1)
2244 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002245
Chris Lattnerac161bf2009-01-02 07:01:27 +00002246 if (unsigned(NameID) != NumberedVals.size())
2247 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002248 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002249
Chris Lattnerac161bf2009-01-02 07:01:27 +00002250 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2251 ForwardRefValIDs.find(NameID);
2252 if (FI != ForwardRefValIDs.end()) {
2253 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002254 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002255 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002256 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002257 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002258 ForwardRefValIDs.erase(FI);
2259 }
2260
2261 NumberedVals.push_back(Inst);
2262 return false;
2263 }
2264
2265 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2266 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2267 FI = ForwardRefVals.find(NameStr);
2268 if (FI != ForwardRefVals.end()) {
2269 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002270 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002271 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002272 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002273 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002274 ForwardRefVals.erase(FI);
2275 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002276
Chris Lattnerac161bf2009-01-02 07:01:27 +00002277 // Set the name on the instruction.
2278 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002279
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002280 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002281 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282 NameStr + "'");
2283 return false;
2284}
2285
2286/// GetBB - Get a basic block with the specified name or ID, creating a
2287/// forward reference record if needed.
2288BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2289 LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002290 return cast_or_null<BasicBlock>(GetVal(Name,
2291 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002292}
2293
2294BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002295 return cast_or_null<BasicBlock>(GetVal(ID,
2296 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002297}
2298
2299/// DefineBB - Define the specified basic block, which is either named or
2300/// unnamed. If there is an error, this returns null otherwise it returns
2301/// the block being defined.
2302BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2303 LocTy Loc) {
2304 BasicBlock *BB;
2305 if (Name.empty())
2306 BB = GetBB(NumberedVals.size(), Loc);
2307 else
2308 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002309 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002310
Chris Lattnerac161bf2009-01-02 07:01:27 +00002311 // Move the block to the end of the function. Forward ref'd blocks are
2312 // inserted wherever they happen to be referenced.
2313 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002314
Chris Lattnerac161bf2009-01-02 07:01:27 +00002315 // Remove the block from forward ref sets.
2316 if (Name.empty()) {
2317 ForwardRefValIDs.erase(NumberedVals.size());
2318 NumberedVals.push_back(BB);
2319 } else {
2320 // BB forward references are already in the function symbol table.
2321 ForwardRefVals.erase(Name);
2322 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002323
Chris Lattnerac161bf2009-01-02 07:01:27 +00002324 return BB;
2325}
2326
2327//===----------------------------------------------------------------------===//
2328// Constants.
2329//===----------------------------------------------------------------------===//
2330
2331/// ParseValID - Parse an abstract value that doesn't necessarily have a
2332/// type implied. For example, if we parse "4" we don't know what integer type
2333/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002334/// sanity. PFS is used to convert function-local operands of metadata (since
2335/// metadata operands are not just parsed here but also converted to values).
2336/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002337bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002338 ID.Loc = Lex.getLoc();
2339 switch (Lex.getKind()) {
2340 default: return TokError("expected value token");
2341 case lltok::GlobalID: // @42
2342 ID.UIntVal = Lex.getUIntVal();
2343 ID.Kind = ValID::t_GlobalID;
2344 break;
2345 case lltok::GlobalVar: // @foo
2346 ID.StrVal = Lex.getStrVal();
2347 ID.Kind = ValID::t_GlobalName;
2348 break;
2349 case lltok::LocalVarID: // %42
2350 ID.UIntVal = Lex.getUIntVal();
2351 ID.Kind = ValID::t_LocalID;
2352 break;
2353 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002354 ID.StrVal = Lex.getStrVal();
2355 ID.Kind = ValID::t_LocalName;
2356 break;
2357 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002358 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002359 ID.Kind = ValID::t_APSInt;
2360 break;
2361 case lltok::APFloat:
2362 ID.APFloatVal = Lex.getAPFloatVal();
2363 ID.Kind = ValID::t_APFloat;
2364 break;
2365 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002366 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002367 ID.Kind = ValID::t_Constant;
2368 break;
2369 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002370 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002371 ID.Kind = ValID::t_Constant;
2372 break;
2373 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2374 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2375 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002376
Chris Lattnerac161bf2009-01-02 07:01:27 +00002377 case lltok::lbrace: {
2378 // ValID ::= '{' ConstVector '}'
2379 Lex.Lex();
2380 SmallVector<Constant*, 16> Elts;
2381 if (ParseGlobalValueVector(Elts) ||
2382 ParseToken(lltok::rbrace, "expected end of struct constant"))
2383 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002384
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002385 ID.ConstantStructElts = new Constant*[Elts.size()];
2386 ID.UIntVal = Elts.size();
2387 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2388 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002389 return false;
2390 }
2391 case lltok::less: {
2392 // ValID ::= '<' ConstVector '>' --> Vector.
2393 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2394 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002395 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002396
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397 SmallVector<Constant*, 16> Elts;
2398 LocTy FirstEltLoc = Lex.getLoc();
2399 if (ParseGlobalValueVector(Elts) ||
2400 (isPackedStruct &&
2401 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2402 ParseToken(lltok::greater, "expected end of constant"))
2403 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002404
Chris Lattnerac161bf2009-01-02 07:01:27 +00002405 if (isPackedStruct) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002406 ID.ConstantStructElts = new Constant*[Elts.size()];
2407 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2408 ID.UIntVal = Elts.size();
2409 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002410 return false;
2411 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002412
Chris Lattnerac161bf2009-01-02 07:01:27 +00002413 if (Elts.empty())
2414 return Error(ID.Loc, "constant vector must not be empty");
2415
Duncan Sands9dff9be2010-02-15 16:12:20 +00002416 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002417 !Elts[0]->getType()->isFloatingPointTy() &&
2418 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002419 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002420 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002421
Chris Lattnerac161bf2009-01-02 07:01:27 +00002422 // Verify that all the vector elements have the same type.
2423 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2424 if (Elts[i]->getType() != Elts[0]->getType())
2425 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002426 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002427 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002428
Chris Lattner69229312011-02-15 00:14:00 +00002429 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002430 ID.Kind = ValID::t_Constant;
2431 return false;
2432 }
2433 case lltok::lsquare: { // Array Constant
2434 Lex.Lex();
2435 SmallVector<Constant*, 16> Elts;
2436 LocTy FirstEltLoc = Lex.getLoc();
2437 if (ParseGlobalValueVector(Elts) ||
2438 ParseToken(lltok::rsquare, "expected end of array constant"))
2439 return true;
2440
2441 // Handle empty element.
2442 if (Elts.empty()) {
2443 // Use undef instead of an array because it's inconvenient to determine
2444 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002445 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002446 return false;
2447 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002448
Chris Lattnerac161bf2009-01-02 07:01:27 +00002449 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002450 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002451 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002452
Owen Anderson4056ca92009-07-29 22:17:13 +00002453 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002454
Chris Lattnerac161bf2009-01-02 07:01:27 +00002455 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002456 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002457 if (Elts[i]->getType() != Elts[0]->getType())
2458 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002459 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002460 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002461 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002462
Jay Foad83be3612011-06-22 09:24:39 +00002463 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002464 ID.Kind = ValID::t_Constant;
2465 return false;
2466 }
2467 case lltok::kw_c: // c "foo"
2468 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002469 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2470 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002471 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2472 ID.Kind = ValID::t_Constant;
2473 return false;
2474
2475 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002476 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2477 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002478 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002479 Lex.Lex();
2480 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002481 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002482 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002483 ParseStringConstant(ID.StrVal) ||
2484 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002485 ParseToken(lltok::StringConstant, "expected constraint string"))
2486 return true;
2487 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002488 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002489 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002490 ID.Kind = ValID::t_InlineAsm;
2491 return false;
2492 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002493
Chris Lattner3432c622009-10-28 03:39:23 +00002494 case lltok::kw_blockaddress: {
2495 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2496 Lex.Lex();
2497
2498 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002499
Chris Lattner3432c622009-10-28 03:39:23 +00002500 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2501 ParseValID(Fn) ||
2502 ParseToken(lltok::comma, "expected comma in block address expression")||
2503 ParseValID(Label) ||
2504 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2505 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002506
Chris Lattner3432c622009-10-28 03:39:23 +00002507 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2508 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002509 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002510 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002511
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002512 // Try to find the function (but skip it if it's forward-referenced).
2513 GlobalValue *GV = nullptr;
2514 if (Fn.Kind == ValID::t_GlobalID) {
2515 if (Fn.UIntVal < NumberedVals.size())
2516 GV = NumberedVals[Fn.UIntVal];
2517 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2518 GV = M->getNamedValue(Fn.StrVal);
2519 }
2520 Function *F = nullptr;
2521 if (GV) {
2522 // Confirm that it's actually a function with a definition.
2523 if (!isa<Function>(GV))
2524 return Error(Fn.Loc, "expected function name in blockaddress");
2525 F = cast<Function>(GV);
2526 if (F->isDeclaration())
2527 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2528 }
2529
2530 if (!F) {
2531 // Make a global variable as a placeholder for this reference.
2532 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2533 if (!FwdRef)
2534 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2535 GlobalValue::InternalLinkage, nullptr, "");
2536 ID.ConstantVal = FwdRef;
2537 ID.Kind = ValID::t_Constant;
2538 return false;
2539 }
2540
2541 // We found the function; now find the basic block. Don't use PFS, since we
2542 // might be inside a constant expression.
2543 BasicBlock *BB;
2544 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2545 if (Label.Kind == ValID::t_LocalID)
2546 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2547 else
2548 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2549 if (!BB)
2550 return Error(Label.Loc, "referenced value is not a basic block");
2551 } else {
2552 if (Label.Kind == ValID::t_LocalID)
2553 return Error(Label.Loc, "cannot take address of numeric label after "
2554 "the function is defined");
2555 BB = dyn_cast_or_null<BasicBlock>(
2556 F->getValueSymbolTable().lookup(Label.StrVal));
2557 if (!BB)
2558 return Error(Label.Loc, "referenced value is not a basic block");
2559 }
2560
2561 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002562 ID.Kind = ValID::t_Constant;
2563 return false;
2564 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002565
Chris Lattnerac161bf2009-01-02 07:01:27 +00002566 case lltok::kw_trunc:
2567 case lltok::kw_zext:
2568 case lltok::kw_sext:
2569 case lltok::kw_fptrunc:
2570 case lltok::kw_fpext:
2571 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002572 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002573 case lltok::kw_uitofp:
2574 case lltok::kw_sitofp:
2575 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002576 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002577 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002578 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002579 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002580 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002581 Constant *SrcVal;
2582 Lex.Lex();
2583 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2584 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002585 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002586 ParseType(DestTy) ||
2587 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2588 return true;
2589 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2590 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002591 getTypeString(SrcVal->getType()) + "' to '" +
2592 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002593 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002594 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002595 ID.Kind = ValID::t_Constant;
2596 return false;
2597 }
2598 case lltok::kw_extractvalue: {
2599 Lex.Lex();
2600 Constant *Val;
2601 SmallVector<unsigned, 4> Indices;
2602 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2603 ParseGlobalTypeAndValue(Val) ||
2604 ParseIndexList(Indices) ||
2605 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2606 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002607
Chris Lattner392be582010-02-12 20:49:41 +00002608 if (!Val->getType()->isAggregateType())
2609 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002610 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002611 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002612 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002613 ID.Kind = ValID::t_Constant;
2614 return false;
2615 }
2616 case lltok::kw_insertvalue: {
2617 Lex.Lex();
2618 Constant *Val0, *Val1;
2619 SmallVector<unsigned, 4> Indices;
2620 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2621 ParseGlobalTypeAndValue(Val0) ||
2622 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2623 ParseGlobalTypeAndValue(Val1) ||
2624 ParseIndexList(Indices) ||
2625 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2626 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002627 if (!Val0->getType()->isAggregateType())
2628 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002629 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002630 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002631 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002632 ID.Kind = ValID::t_Constant;
2633 return false;
2634 }
2635 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002636 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002637 unsigned PredVal, Opc = Lex.getUIntVal();
2638 Constant *Val0, *Val1;
2639 Lex.Lex();
2640 if (ParseCmpPredicate(PredVal, Opc) ||
2641 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2642 ParseGlobalTypeAndValue(Val0) ||
2643 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2644 ParseGlobalTypeAndValue(Val1) ||
2645 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2646 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002647
Chris Lattnerac161bf2009-01-02 07:01:27 +00002648 if (Val0->getType() != Val1->getType())
2649 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002650
Chris Lattnerac161bf2009-01-02 07:01:27 +00002651 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002652
Chris Lattnerac161bf2009-01-02 07:01:27 +00002653 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002654 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002655 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002656 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002657 } else {
2658 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002659 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002660 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002661 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002662 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002663 }
2664 ID.Kind = ValID::t_Constant;
2665 return false;
2666 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002667
Chris Lattnerac161bf2009-01-02 07:01:27 +00002668 // Binary Operators.
2669 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002670 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002671 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002672 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002673 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002674 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002675 case lltok::kw_udiv:
2676 case lltok::kw_sdiv:
2677 case lltok::kw_fdiv:
2678 case lltok::kw_urem:
2679 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002680 case lltok::kw_frem:
2681 case lltok::kw_shl:
2682 case lltok::kw_lshr:
2683 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002684 bool NUW = false;
2685 bool NSW = false;
2686 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002687 unsigned Opc = Lex.getUIntVal();
2688 Constant *Val0, *Val1;
2689 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002690 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002691 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2692 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002693 if (EatIfPresent(lltok::kw_nuw))
2694 NUW = true;
2695 if (EatIfPresent(lltok::kw_nsw)) {
2696 NSW = true;
2697 if (EatIfPresent(lltok::kw_nuw))
2698 NUW = true;
2699 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002700 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2701 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002702 if (EatIfPresent(lltok::kw_exact))
2703 Exact = true;
2704 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002705 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2706 ParseGlobalTypeAndValue(Val0) ||
2707 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2708 ParseGlobalTypeAndValue(Val1) ||
2709 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2710 return true;
2711 if (Val0->getType() != Val1->getType())
2712 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002713 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002714 if (NUW)
2715 return Error(ModifierLoc, "nuw only applies to integer operations");
2716 if (NSW)
2717 return Error(ModifierLoc, "nsw only applies to integer operations");
2718 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002719 // Check that the type is valid for the operator.
2720 switch (Opc) {
2721 case Instruction::Add:
2722 case Instruction::Sub:
2723 case Instruction::Mul:
2724 case Instruction::UDiv:
2725 case Instruction::SDiv:
2726 case Instruction::URem:
2727 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002728 case Instruction::Shl:
2729 case Instruction::AShr:
2730 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002731 if (!Val0->getType()->isIntOrIntVectorTy())
2732 return Error(ID.Loc, "constexpr requires integer operands");
2733 break;
2734 case Instruction::FAdd:
2735 case Instruction::FSub:
2736 case Instruction::FMul:
2737 case Instruction::FDiv:
2738 case Instruction::FRem:
2739 if (!Val0->getType()->isFPOrFPVectorTy())
2740 return Error(ID.Loc, "constexpr requires fp operands");
2741 break;
2742 default: llvm_unreachable("Unknown binary operator!");
2743 }
Dan Gohman1b849082009-09-07 23:54:19 +00002744 unsigned Flags = 0;
2745 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2746 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002747 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002748 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002749 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002750 ID.Kind = ValID::t_Constant;
2751 return false;
2752 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002753
Chris Lattnerac161bf2009-01-02 07:01:27 +00002754 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002755 case lltok::kw_and:
2756 case lltok::kw_or:
2757 case lltok::kw_xor: {
2758 unsigned Opc = Lex.getUIntVal();
2759 Constant *Val0, *Val1;
2760 Lex.Lex();
2761 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2762 ParseGlobalTypeAndValue(Val0) ||
2763 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2764 ParseGlobalTypeAndValue(Val1) ||
2765 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2766 return true;
2767 if (Val0->getType() != Val1->getType())
2768 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002769 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002770 return Error(ID.Loc,
2771 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002772 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002773 ID.Kind = ValID::t_Constant;
2774 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002775 }
2776
Chris Lattnerac161bf2009-01-02 07:01:27 +00002777 case lltok::kw_getelementptr:
2778 case lltok::kw_shufflevector:
2779 case lltok::kw_insertelement:
2780 case lltok::kw_extractelement:
2781 case lltok::kw_select: {
2782 unsigned Opc = Lex.getUIntVal();
2783 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002784 bool InBounds = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002785 Lex.Lex();
Dan Gohman1639c392009-07-27 21:53:46 +00002786 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002787 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002788 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2789 ParseGlobalValueVector(Elts) ||
2790 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2791 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002792
Chris Lattnerac161bf2009-01-02 07:01:27 +00002793 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002794 if (Elts.size() == 0 ||
2795 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002796 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002797
Jay Foaded8db7d2011-07-21 14:31:17 +00002798 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foadd1b78492011-07-25 09:48:08 +00002799 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002800 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002801 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2802 InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002803 } else if (Opc == Instruction::Select) {
2804 if (Elts.size() != 3)
2805 return Error(ID.Loc, "expected three operands to select");
2806 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2807 Elts[2]))
2808 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002809 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002810 } else if (Opc == Instruction::ShuffleVector) {
2811 if (Elts.size() != 3)
2812 return Error(ID.Loc, "expected three operands to shufflevector");
2813 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2814 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002815 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002816 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002817 } else if (Opc == Instruction::ExtractElement) {
2818 if (Elts.size() != 2)
2819 return Error(ID.Loc, "expected two operands to extractelement");
2820 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2821 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002822 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002823 } else {
2824 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2825 if (Elts.size() != 3)
2826 return Error(ID.Loc, "expected three operands to insertelement");
2827 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2828 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002829 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002830 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002831 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002832
Chris Lattnerac161bf2009-01-02 07:01:27 +00002833 ID.Kind = ValID::t_Constant;
2834 return false;
2835 }
2836 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002837
Chris Lattnerac161bf2009-01-02 07:01:27 +00002838 Lex.Lex();
2839 return false;
2840}
2841
2842/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002843bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002844 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002845 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002846 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002847 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002848 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002849 if (V && !(C = dyn_cast<Constant>(V)))
2850 return Error(ID.Loc, "global values must be constants");
2851 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002852}
2853
Victor Hernandez9d75c962010-01-11 22:31:58 +00002854bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002855 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002856 return ParseType(Ty) ||
2857 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002858}
2859
Rafael Espindola83a362c2015-01-06 22:55:16 +00002860bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002861 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002862
2863 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002864 if (!EatIfPresent(lltok::kw_comdat))
2865 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002866
2867 if (EatIfPresent(lltok::lparen)) {
2868 if (Lex.getKind() != lltok::ComdatVar)
2869 return TokError("expected comdat variable");
2870 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2871 Lex.Lex();
2872 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2873 return true;
2874 } else {
2875 if (GlobalName.empty())
2876 return TokError("comdat cannot be unnamed");
2877 C = getComdat(GlobalName, KwLoc);
2878 }
2879
David Majnemerdad0a642014-06-27 18:19:56 +00002880 return false;
2881}
2882
Victor Hernandez9d75c962010-01-11 22:31:58 +00002883/// ParseGlobalValueVector
2884/// ::= /*empty*/
2885/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002886bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002887 // Empty list.
2888 if (Lex.getKind() == lltok::rbrace ||
2889 Lex.getKind() == lltok::rsquare ||
2890 Lex.getKind() == lltok::greater ||
2891 Lex.getKind() == lltok::rparen)
2892 return false;
2893
2894 Constant *C;
2895 if (ParseGlobalTypeAndValue(C)) return true;
2896 Elts.push_back(C);
2897
2898 while (EatIfPresent(lltok::comma)) {
2899 if (ParseGlobalTypeAndValue(C)) return true;
2900 Elts.push_back(C);
2901 }
2902
2903 return false;
2904}
2905
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00002906bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002907 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002908 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00002909 return true;
2910
Duncan P. N. Exon Smithdbcff302015-01-12 22:23:04 +00002911 MD = (IsDistinct ? MDNode::getDistinct : MDNode::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00002912 return false;
2913}
2914
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002915/// ParseMetadataAsValue
2916/// ::= metadata i32 %local
2917/// ::= metadata i32 @global
2918/// ::= metadata i32 7
2919/// ::= metadata !0
2920/// ::= metadata !{...}
2921/// ::= metadata !"string"
2922bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
2923 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002924 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002925 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002926 return true;
2927
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002928 V = MetadataAsValue::get(Context, MD);
2929 return false;
2930}
2931
2932/// ParseValueAsMetadata
2933/// ::= i32 %local
2934/// ::= i32 @global
2935/// ::= i32 7
2936bool LLParser::ParseValueAsMetadata(Metadata *&MD, PerFunctionState *PFS) {
2937 Type *Ty;
2938 LocTy Loc;
2939 if (ParseType(Ty, "expected metadata operand", Loc))
2940 return true;
2941 if (Ty->isMetadataTy())
2942 return Error(Loc, "invalid metadata-value-metadata roundtrip");
2943
2944 Value *V;
2945 if (ParseValue(Ty, V, PFS))
2946 return true;
2947
2948 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002949 return false;
2950}
2951
2952/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002953/// ::= i32 %local
2954/// ::= i32 @global
2955/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00002956/// ::= !42
2957/// ::= !{...}
2958/// ::= !"string"
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002959bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002960 // ValueAsMetadata:
2961 // <type> <value>
2962 if (Lex.getKind() != lltok::exclaim)
2963 return ParseValueAsMetadata(MD, PFS);
2964
2965 // '!'.
2966 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
2967 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00002968
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00002969 // MDString:
2970 // ::= '!' STRINGCONSTANT
2971 if (Lex.getKind() == lltok::StringConstant) {
2972 MDString *S;
2973 if (ParseMDString(S))
2974 return true;
2975 MD = S;
2976 return false;
2977 }
2978
Dan Gohman8939ba332010-07-14 18:26:50 +00002979 // MDNode:
2980 // !{ ... }
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002981 if (Lex.getKind() == lltok::lbrace) {
2982 MDNode *N;
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00002983 if (ParseMDTuple(N))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002984 return true;
2985 MD = N;
2986 return false;
2987 }
Dan Gohman8939ba332010-07-14 18:26:50 +00002988
2989 // Standalone metadata reference
2990 // !42
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00002991 MDNode *N;
2992 if (ParseMDNodeID(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002993 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00002994 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00002995 return false;
2996}
2997
Victor Hernandez9d75c962010-01-11 22:31:58 +00002998
2999//===----------------------------------------------------------------------===//
3000// Function Parsing.
3001//===----------------------------------------------------------------------===//
3002
Chris Lattner229907c2011-07-18 04:54:35 +00003003bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003004 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003005 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003006 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003007
Chris Lattnerac161bf2009-01-02 07:01:27 +00003008 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003009 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003010 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3011 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003012 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003013 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003014 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3015 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003016 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003017 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003018 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003019 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003020 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003021 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3022 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003023 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003024 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003025 return false;
3026 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003027 case ValID::t_GlobalName:
3028 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003029 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003030 case ValID::t_GlobalID:
3031 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003032 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003033 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003034 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003035 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003036 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003037 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003038 return false;
3039 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003040 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003041 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3042 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003043
Dan Gohman518cda42011-12-17 00:04:22 +00003044 // The lexer has no type info, so builds all half, float, and double FP
3045 // constants as double. Fix this here. Long double does not need this.
3046 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003047 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003048 if (Ty->isHalfTy())
3049 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3050 &Ignored);
3051 else if (Ty->isFloatTy())
3052 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3053 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003054 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003055 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003056
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003057 if (V->getType() != Ty)
3058 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003059 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003060
Chris Lattnerac161bf2009-01-02 07:01:27 +00003061 return false;
3062 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003063 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003064 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003065 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003066 return false;
3067 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003068 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003069 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003070 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003071 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003072 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00003073 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00003074 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00003075 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003076 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00003077 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003078 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00003079 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00003080 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003081 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00003082 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003083 return false;
3084 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00003085 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003086 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00003087
Chris Lattnerac161bf2009-01-02 07:01:27 +00003088 V = ID.ConstantVal;
3089 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003090 case ValID::t_ConstantStruct:
3091 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00003092 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003093 if (ST->getNumElements() != ID.UIntVal)
3094 return Error(ID.Loc,
3095 "initializer with struct type has wrong # elements");
3096 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3097 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003098
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003099 // Verify that the elements are compatible with the structtype.
3100 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3101 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3102 return Error(ID.Loc, "element " + Twine(i) +
3103 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003104
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003105 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3106 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003107 } else
3108 return Error(ID.Loc, "constant expression type mismatch");
3109 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003110 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00003111 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003112}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003113
Chris Lattner229907c2011-07-18 04:54:35 +00003114bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003115 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003116 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003117 return ParseValID(ID, PFS) ||
3118 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003119}
3120
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003121bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003122 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003123 return ParseType(Ty) ||
3124 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003125}
3126
Chris Lattner3ed871f2009-10-27 19:13:16 +00003127bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3128 PerFunctionState &PFS) {
3129 Value *V;
3130 Loc = Lex.getLoc();
3131 if (ParseTypeAndValue(V, PFS)) return true;
3132 if (!isa<BasicBlock>(V))
3133 return Error(Loc, "expected a basic block");
3134 BB = cast<BasicBlock>(V);
3135 return false;
3136}
3137
3138
Chris Lattnerac161bf2009-01-02 07:01:27 +00003139/// FunctionHeader
3140/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00003141/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003142/// OptionalAlign OptGC OptionalPrefix OptionalPrologue
Chris Lattnerac161bf2009-01-02 07:01:27 +00003143bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3144 // Parse the linkage.
3145 LocTy LinkageLoc = Lex.getLoc();
3146 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003147
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00003148 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00003149 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00003150 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003151 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003152 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003153 LocTy RetTypeLoc = Lex.getLoc();
3154 if (ParseOptionalLinkage(Linkage) ||
3155 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00003156 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003157 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003158 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003159 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003160 return true;
3161
3162 // Verify that the linkage is ok.
3163 switch ((GlobalValue::LinkageTypes)Linkage) {
3164 case GlobalValue::ExternalLinkage:
3165 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00003166 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003167 if (isDefine)
3168 return Error(LinkageLoc, "invalid linkage for function definition");
3169 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00003170 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003171 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00003172 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00003173 case GlobalValue::LinkOnceAnyLinkage:
3174 case GlobalValue::LinkOnceODRLinkage:
3175 case GlobalValue::WeakAnyLinkage:
3176 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003177 if (!isDefine)
3178 return Error(LinkageLoc, "invalid linkage for function declaration");
3179 break;
3180 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00003181 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003182 return Error(LinkageLoc, "invalid function linkage type");
3183 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003184
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003185 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3186 return Error(LinkageLoc,
3187 "symbol with local linkage must have default visibility");
3188
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003189 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003190 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003191
Chris Lattnerac161bf2009-01-02 07:01:27 +00003192 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00003193
3194 std::string FunctionName;
3195 if (Lex.getKind() == lltok::GlobalVar) {
3196 FunctionName = Lex.getStrVal();
3197 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3198 unsigned NameID = Lex.getUIntVal();
3199
3200 if (NameID != NumberedVals.size())
3201 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003202 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00003203 } else {
3204 return TokError("expected function name");
3205 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003206
Chris Lattner3822f632009-01-02 08:05:26 +00003207 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003208
Chris Lattner3822f632009-01-02 08:05:26 +00003209 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003210 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003211
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003212 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003213 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00003214 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003215 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00003216 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003217 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003218 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00003219 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003220 bool UnnamedAddr;
3221 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00003222 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003223 Constant *Prologue = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00003224 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00003225
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003226 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00003227 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3228 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003229 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00003230 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003231 (EatIfPresent(lltok::kw_section) &&
3232 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00003233 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00003234 ParseOptionalAlignment(Alignment) ||
3235 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003236 ParseStringConstant(GC)) ||
3237 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003238 ParseGlobalTypeAndValue(Prefix)) ||
3239 (EatIfPresent(lltok::kw_prologue) &&
3240 ParseGlobalTypeAndValue(Prologue)))
Chris Lattner3822f632009-01-02 08:05:26 +00003241 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003242
Michael Gottesman41748d72013-06-27 00:25:01 +00003243 if (FuncAttrs.contains(Attribute::Builtin))
3244 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00003245
Chris Lattnerac161bf2009-01-02 07:01:27 +00003246 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00003247 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00003248 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003249 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003250 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003251
Chris Lattnerac161bf2009-01-02 07:01:27 +00003252 // Okay, if we got here, the function is syntactically valid. Convert types
3253 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00003254 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00003255 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003256
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003257 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003258 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3259 AttributeSet::ReturnIndex,
3260 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003261
Chris Lattnerac161bf2009-01-02 07:01:27 +00003262 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003263 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003264 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3265 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003266 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3267 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003268 }
3269
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003270 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003271 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3272 AttributeSet::FunctionIndex,
3273 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003274
Bill Wendlinge94d8432012-12-07 23:16:57 +00003275 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003276
Bill Wendling749a43d2012-12-30 13:50:49 +00003277 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003278 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3279
Chris Lattner229907c2011-07-18 04:54:35 +00003280 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00003281 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00003282 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003283
Craig Topper2617dcc2014-04-15 06:32:26 +00003284 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003285 if (!FunctionName.empty()) {
3286 // If this was a definition of a forward reference, remove the definition
3287 // from the forward reference table and fill in the forward ref.
3288 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3289 ForwardRefVals.find(FunctionName);
3290 if (FRVI != ForwardRefVals.end()) {
3291 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00003292 if (!Fn)
3293 return Error(FRVI->second.second, "invalid forward reference to "
3294 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00003295 if (Fn->getType() != PFT)
3296 return Error(FRVI->second.second, "invalid forward reference to "
3297 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003298
Chris Lattnerac161bf2009-01-02 07:01:27 +00003299 ForwardRefVals.erase(FRVI);
3300 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00003301 // Reject redefinitions.
3302 return Error(NameLoc, "invalid redefinition of function '" +
3303 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00003304 } else if (M->getNamedValue(FunctionName)) {
3305 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003306 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003307
Dan Gohman399d6ae2009-08-29 23:37:49 +00003308 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003309 // If this is a definition of a forward referenced function, make sure the
3310 // types agree.
3311 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3312 = ForwardRefValIDs.find(NumberedVals.size());
3313 if (I != ForwardRefValIDs.end()) {
3314 Fn = cast<Function>(I->second.first);
3315 if (Fn->getType() != PFT)
3316 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00003317 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003318 ForwardRefValIDs.erase(I);
3319 }
3320 }
3321
Craig Topper2617dcc2014-04-15 06:32:26 +00003322 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003323 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3324 else // Move the forward-reference to the correct spot in the module.
3325 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3326
3327 if (FunctionName.empty())
3328 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003329
Chris Lattnerac161bf2009-01-02 07:01:27 +00003330 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3331 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00003332 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003333 Fn->setCallingConv(CC);
3334 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003335 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003336 Fn->setAlignment(Alignment);
3337 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00003338 Fn->setComdat(C);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003339 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003340 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003341 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003342 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003343
Chris Lattnerac161bf2009-01-02 07:01:27 +00003344 // Add all of the arguments we parsed to the function.
3345 Function::arg_iterator ArgIt = Fn->arg_begin();
3346 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3347 // If the argument has a name, insert it into the argument symbol table.
3348 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003349
Chris Lattnerac161bf2009-01-02 07:01:27 +00003350 // Set the name, if it conflicted, it will be auto-renamed.
3351 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003352
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00003353 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003354 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3355 ArgList[i].Name + "'");
3356 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003357
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003358 if (isDefine)
3359 return false;
3360
Robin Morisset039781e2014-08-29 21:53:01 +00003361 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003362 ValID ID;
3363 if (FunctionName.empty()) {
3364 ID.Kind = ValID::t_GlobalID;
3365 ID.UIntVal = NumberedVals.size() - 1;
3366 } else {
3367 ID.Kind = ValID::t_GlobalName;
3368 ID.StrVal = FunctionName;
3369 }
3370 auto Blocks = ForwardRefBlockAddresses.find(ID);
3371 if (Blocks != ForwardRefBlockAddresses.end())
3372 return Error(Blocks->first.Loc,
3373 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003374 return false;
3375}
3376
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003377bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3378 ValID ID;
3379 if (FunctionNumber == -1) {
3380 ID.Kind = ValID::t_GlobalName;
3381 ID.StrVal = F.getName();
3382 } else {
3383 ID.Kind = ValID::t_GlobalID;
3384 ID.UIntVal = FunctionNumber;
3385 }
3386
3387 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3388 if (Blocks == P.ForwardRefBlockAddresses.end())
3389 return false;
3390
3391 for (const auto &I : Blocks->second) {
3392 const ValID &BBID = I.first;
3393 GlobalValue *GV = I.second;
3394
3395 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3396 "Expected local id or name");
3397 BasicBlock *BB;
3398 if (BBID.Kind == ValID::t_LocalName)
3399 BB = GetBB(BBID.StrVal, BBID.Loc);
3400 else
3401 BB = GetBB(BBID.UIntVal, BBID.Loc);
3402 if (!BB)
3403 return P.Error(BBID.Loc, "referenced value is not a basic block");
3404
3405 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3406 GV->eraseFromParent();
3407 }
3408
3409 P.ForwardRefBlockAddresses.erase(Blocks);
3410 return false;
3411}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003412
3413/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003414/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00003415bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00003416 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003417 return TokError("expected '{' in function body");
3418 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003419
Chris Lattner3432c622009-10-28 03:39:23 +00003420 int FunctionNumber = -1;
3421 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003422
Chris Lattner3432c622009-10-28 03:39:23 +00003423 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003424
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00003425 // Resolve block addresses and allow basic blocks to be forward-declared
3426 // within this function.
3427 if (PFS.resolveForwardRefBlockAddresses())
3428 return true;
3429 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3430
Chris Lattnerbbddd962010-01-09 19:20:07 +00003431 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003432 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00003433 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003434
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003435 while (Lex.getKind() != lltok::rbrace &&
3436 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003437 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003438
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003439 while (Lex.getKind() != lltok::rbrace)
3440 if (ParseUseListOrder(&PFS))
3441 return true;
3442
Chris Lattnerac161bf2009-01-02 07:01:27 +00003443 // Eat the }.
3444 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003445
Chris Lattnerac161bf2009-01-02 07:01:27 +00003446 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00003447 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003448}
3449
3450/// ParseBasicBlock
3451/// ::= LabelStr? Instruction*
3452bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3453 // If this basic block starts out with a name, remember it.
3454 std::string Name;
3455 LocTy NameLoc = Lex.getLoc();
3456 if (Lex.getKind() == lltok::LabelStr) {
3457 Name = Lex.getStrVal();
3458 Lex.Lex();
3459 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003460
Chris Lattnerac161bf2009-01-02 07:01:27 +00003461 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003462 if (!BB) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003463
Chris Lattnerac161bf2009-01-02 07:01:27 +00003464 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003465
Chris Lattnerac161bf2009-01-02 07:01:27 +00003466 // Parse the instructions in this block until we get a terminator.
3467 Instruction *Inst;
3468 do {
3469 // This instruction may have three possibilities for a name: a) none
3470 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3471 LocTy NameLoc = Lex.getLoc();
3472 int NameID = -1;
3473 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003474
Chris Lattnerac161bf2009-01-02 07:01:27 +00003475 if (Lex.getKind() == lltok::LocalVarID) {
3476 NameID = Lex.getUIntVal();
3477 Lex.Lex();
3478 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3479 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00003480 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003481 NameStr = Lex.getStrVal();
3482 Lex.Lex();
3483 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3484 return true;
3485 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003486
Chris Lattner77b89dc2009-12-30 05:23:43 +00003487 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00003488 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00003489 case InstError: return true;
3490 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003491 BB->getInstList().push_back(Inst);
3492
Chris Lattner77b89dc2009-12-30 05:23:43 +00003493 // With a normal result, we check to see if the instruction is followed by
3494 // a comma and metadata.
3495 if (EatIfPresent(lltok::comma))
Dan Gohman338d9a42010-08-24 02:05:17 +00003496 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003497 return true;
3498 break;
3499 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00003500 BB->getInstList().push_back(Inst);
3501
Chris Lattner77b89dc2009-12-30 05:23:43 +00003502 // If the instruction parser ate an extra comma at the end of it, it
3503 // *must* be followed by metadata.
Dan Gohman338d9a42010-08-24 02:05:17 +00003504 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattner77b89dc2009-12-30 05:23:43 +00003505 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003506 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00003507 }
Devang Patelea8a4b92009-09-17 23:04:48 +00003508
Chris Lattnerac161bf2009-01-02 07:01:27 +00003509 // Set the name on the instruction.
3510 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3511 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003512
Chris Lattnerac161bf2009-01-02 07:01:27 +00003513 return false;
3514}
3515
3516//===----------------------------------------------------------------------===//
3517// Instruction Parsing.
3518//===----------------------------------------------------------------------===//
3519
3520/// ParseInstruction - Parse one of the many different instructions.
3521///
Chris Lattner77b89dc2009-12-30 05:23:43 +00003522int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3523 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003524 lltok::Kind Token = Lex.getKind();
3525 if (Token == lltok::Eof)
3526 return TokError("found end of file when expecting more instructions");
3527 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00003528 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00003529 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003530
Chris Lattnerac161bf2009-01-02 07:01:27 +00003531 switch (Token) {
3532 default: return Error(Loc, "expected instruction opcode");
3533 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00003534 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003535 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3536 case lltok::kw_br: return ParseBr(Inst, PFS);
3537 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003538 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003539 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003540 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003541 // Binary Operators.
3542 case lltok::kw_add:
3543 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003544 case lltok::kw_mul:
3545 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00003546 bool NUW = EatIfPresent(lltok::kw_nuw);
3547 bool NSW = EatIfPresent(lltok::kw_nsw);
3548 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003549
Chris Lattnera676c0f2011-02-07 16:40:21 +00003550 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003551
Chris Lattnera676c0f2011-02-07 16:40:21 +00003552 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3553 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3554 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003555 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003556 case lltok::kw_fadd:
3557 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00003558 case lltok::kw_fmul:
3559 case lltok::kw_fdiv:
3560 case lltok::kw_frem: {
3561 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3562 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3563 if (Res != 0)
3564 return Res;
3565 if (FMF.any())
3566 Inst->setFastMathFlags(FMF);
3567 return 0;
3568 }
Dan Gohmana5b96452009-06-04 22:49:04 +00003569
Chris Lattner35315d02011-02-06 21:44:57 +00003570 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003571 case lltok::kw_udiv:
3572 case lltok::kw_lshr:
3573 case lltok::kw_ashr: {
3574 bool Exact = EatIfPresent(lltok::kw_exact);
3575
3576 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3577 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3578 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00003579 }
3580
Chris Lattnerac161bf2009-01-02 07:01:27 +00003581 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00003582 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003583 case lltok::kw_and:
3584 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00003585 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003586 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003587 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003588 // Casts.
3589 case lltok::kw_trunc:
3590 case lltok::kw_zext:
3591 case lltok::kw_sext:
3592 case lltok::kw_fptrunc:
3593 case lltok::kw_fpext:
3594 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003595 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003596 case lltok::kw_uitofp:
3597 case lltok::kw_sitofp:
3598 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003599 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003600 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00003601 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003602 // Other.
3603 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00003604 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003605 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3606 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3607 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3608 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00003609 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00003610 // Call.
3611 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3612 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3613 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003614 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00003615 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00003616 case lltok::kw_load: return ParseLoad(Inst, PFS);
3617 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00003618 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3619 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003620 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003621 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3622 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3623 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3624 }
3625}
3626
3627/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3628bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003629 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003630 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003631 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003632 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3633 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3634 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3635 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3636 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3637 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3638 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3639 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3640 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3641 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3642 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3643 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3644 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3645 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3646 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3647 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3648 }
3649 } else {
3650 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00003651 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003652 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3653 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3654 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3655 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3656 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3657 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3658 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3659 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3660 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3661 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3662 }
3663 }
3664 Lex.Lex();
3665 return false;
3666}
3667
3668//===----------------------------------------------------------------------===//
3669// Terminator Instructions.
3670//===----------------------------------------------------------------------===//
3671
3672/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00003673/// ::= 'ret' void (',' !dbg, !1)*
3674/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00003675bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003676 PerFunctionState &PFS) {
3677 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00003678 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00003679 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003680
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003681 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003682
Chris Lattnerfdd87902009-10-05 05:54:46 +00003683 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003684 if (!ResType->isVoidTy())
3685 return Error(TypeLoc, "value doesn't match function result type '" +
3686 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003687
Owen Anderson55f1c092009-08-13 21:58:54 +00003688 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003689 return false;
3690 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003691
Chris Lattnerac161bf2009-01-02 07:01:27 +00003692 Value *RV;
3693 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003694
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003695 if (ResType != RV->getType())
3696 return Error(TypeLoc, "value doesn't match function result type '" +
3697 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003698
Owen Anderson55f1c092009-08-13 21:58:54 +00003699 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00003700 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003701}
3702
3703
3704/// ParseBr
3705/// ::= 'br' TypeAndValue
3706/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3707bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3708 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003709 Value *Op0;
3710 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003711 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003712
Chris Lattnerac161bf2009-01-02 07:01:27 +00003713 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3714 Inst = BranchInst::Create(BB);
3715 return false;
3716 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003717
Owen Anderson55f1c092009-08-13 21:58:54 +00003718 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003719 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003720
Chris Lattnerac161bf2009-01-02 07:01:27 +00003721 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003722 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003723 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003724 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003725 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003726
Chris Lattner3ed871f2009-10-27 19:13:16 +00003727 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003728 return false;
3729}
3730
3731/// ParseSwitch
3732/// Instruction
3733/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3734/// JumpTable
3735/// ::= (TypeAndValue ',' TypeAndValue)*
3736bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3737 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00003738 Value *Cond;
3739 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003740 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3741 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003742 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003743 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3744 return true;
3745
Duncan Sands19d0b472010-02-16 11:11:14 +00003746 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003747 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003748
Chris Lattnerac161bf2009-01-02 07:01:27 +00003749 // Parse the jump table pairs.
3750 SmallPtrSet<Value*, 32> SeenCases;
3751 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3752 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003753 Value *Constant;
3754 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003755
Chris Lattnerac161bf2009-01-02 07:01:27 +00003756 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3757 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003758 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003759 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003760
David Blaikie70573dc2014-11-19 07:49:26 +00003761 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00003762 return Error(CondLoc, "duplicate case value in switch");
3763 if (!isa<ConstantInt>(Constant))
3764 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003765
Chris Lattner3ed871f2009-10-27 19:13:16 +00003766 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003767 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003768
Chris Lattnerac161bf2009-01-02 07:01:27 +00003769 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003770
Chris Lattner3ed871f2009-10-27 19:13:16 +00003771 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00003772 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3773 SI->addCase(Table[i].first, Table[i].second);
3774 Inst = SI;
3775 return false;
3776}
3777
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003778/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00003779/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003780/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3781bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00003782 LocTy AddrLoc;
3783 Value *Address;
3784 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003785 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3786 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00003787 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003788
Duncan Sands19d0b472010-02-16 11:11:14 +00003789 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003790 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003791
Chris Lattner3ed871f2009-10-27 19:13:16 +00003792 // Parse the destination list.
3793 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003794
Chris Lattner3ed871f2009-10-27 19:13:16 +00003795 if (Lex.getKind() != lltok::rsquare) {
3796 BasicBlock *DestBB;
3797 if (ParseTypeAndBasicBlock(DestBB, PFS))
3798 return true;
3799 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003800
Chris Lattner3ed871f2009-10-27 19:13:16 +00003801 while (EatIfPresent(lltok::comma)) {
3802 if (ParseTypeAndBasicBlock(DestBB, PFS))
3803 return true;
3804 DestList.push_back(DestBB);
3805 }
3806 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003807
Chris Lattner3ed871f2009-10-27 19:13:16 +00003808 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3809 return true;
3810
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003811 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00003812 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3813 IBI->addDestination(DestList[i]);
3814 Inst = IBI;
3815 return false;
3816}
3817
3818
Chris Lattnerac161bf2009-01-02 07:01:27 +00003819/// ParseInvoke
3820/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3821/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3822bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3823 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00003824 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00003825 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00003826 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00003827 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00003828 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003829 LocTy RetTypeLoc;
3830 ValID CalleeID;
3831 SmallVector<ParamInfo, 16> ArgList;
3832
Chris Lattner3ed871f2009-10-27 19:13:16 +00003833 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003834 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00003835 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00003836 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003837 ParseValID(CalleeID) ||
3838 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00003839 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3840 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003841 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003842 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003843 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00003844 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00003845 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003846
Chris Lattnerac161bf2009-01-02 07:01:27 +00003847 // If RetType is a non-function pointer type, then this is the short syntax
3848 // for the call, which means that RetType is just the return type. Infer the
3849 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00003850 PointerType *PFTy = nullptr;
3851 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003852 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3853 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3854 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00003855 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003856 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3857 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003858
Chris Lattnerac161bf2009-01-02 07:01:27 +00003859 if (!FunctionType::isValidReturnType(RetType))
3860 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003861
Owen Anderson4056ca92009-07-29 22:17:13 +00003862 Ty = FunctionType::get(RetType, ParamTypes, false);
3863 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003864 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003865
Chris Lattnerac161bf2009-01-02 07:01:27 +00003866 // Look up the callee.
3867 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003868 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003869
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003870 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00003871 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003872 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003873 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3874 AttributeSet::ReturnIndex,
3875 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003876
Chris Lattnerac161bf2009-01-02 07:01:27 +00003877 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003878
Chris Lattnerac161bf2009-01-02 07:01:27 +00003879 // Loop through FunctionType's arguments and ensure they are specified
3880 // correctly. Also, gather any parameter attributes.
3881 FunctionType::param_iterator I = Ty->param_begin();
3882 FunctionType::param_iterator E = Ty->param_end();
3883 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003884 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003885 if (I != E) {
3886 ExpectedTy = *I++;
3887 } else if (!Ty->isVarArg()) {
3888 return Error(ArgList[i].Loc, "too many arguments specified");
3889 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003890
Chris Lattnerac161bf2009-01-02 07:01:27 +00003891 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3892 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003893 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00003894 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00003895 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3896 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00003897 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3898 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003899 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003900
Chris Lattnerac161bf2009-01-02 07:01:27 +00003901 if (I != E)
3902 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003903
Bill Wendling3bef2dd2012-09-19 23:54:18 +00003904 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00003905 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3906 AttributeSet::FunctionIndex,
3907 FnAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003908
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003909 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00003910 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003911
Jay Foad5bd375a2011-07-15 08:37:34 +00003912 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003913 II->setCallingConv(CC);
3914 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00003915 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003916 Inst = II;
3917 return false;
3918}
3919
Bill Wendlingf891bf82011-07-31 06:30:59 +00003920/// ParseResume
3921/// ::= 'resume' TypeAndValue
3922bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3923 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003924 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3925 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003926
Bill Wendlingf891bf82011-07-31 06:30:59 +00003927 ResumeInst *RI = ResumeInst::Create(Exn);
3928 Inst = RI;
3929 return false;
3930}
Chris Lattnerac161bf2009-01-02 07:01:27 +00003931
3932//===----------------------------------------------------------------------===//
3933// Binary Operators.
3934//===----------------------------------------------------------------------===//
3935
3936/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003937/// ::= ArithmeticOps TypeAndValue ',' Value
3938///
3939/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3940/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00003941bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003942 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003943 LocTy Loc; Value *LHS, *RHS;
3944 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3945 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3946 ParseValue(LHS->getType(), RHS, PFS))
3947 return true;
3948
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003949 bool Valid;
3950 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003951 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003952 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003953 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3954 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003955 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00003956 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3957 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003958 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003959
Chris Lattnereeefa9a2009-01-05 08:24:46 +00003960 if (!Valid)
3961 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003962
Chris Lattnerac161bf2009-01-02 07:01:27 +00003963 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3964 return false;
3965}
3966
3967/// ParseLogical
3968/// ::= ArithmeticOps TypeAndValue ',' Value {
3969bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3970 unsigned Opc) {
3971 LocTy Loc; Value *LHS, *RHS;
3972 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3973 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3974 ParseValue(LHS->getType(), RHS, PFS))
3975 return true;
3976
Duncan Sands9dff9be2010-02-15 16:12:20 +00003977 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003978 return Error(Loc,"instruction requires integer or integer vector operands");
3979
3980 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3981 return false;
3982}
3983
3984
3985/// ParseCompare
3986/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3987/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00003988bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3989 unsigned Opc) {
3990 // Parse the integer/fp comparison predicate.
3991 LocTy Loc;
3992 unsigned Pred;
3993 Value *LHS, *RHS;
3994 if (ParseCmpPredicate(Pred, Opc) ||
3995 ParseTypeAndValue(LHS, Loc, PFS) ||
3996 ParseToken(lltok::comma, "expected ',' after compare value") ||
3997 ParseValue(LHS->getType(), RHS, PFS))
3998 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003999
Chris Lattnerac161bf2009-01-02 07:01:27 +00004000 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00004001 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004002 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004003 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004004 } else {
4005 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00004006 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00004007 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004008 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004009 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004010 }
4011 return false;
4012}
4013
4014//===----------------------------------------------------------------------===//
4015// Other Instructions.
4016//===----------------------------------------------------------------------===//
4017
4018
4019/// ParseCast
4020/// ::= CastOpc TypeAndValue 'to' Type
4021bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4022 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004023 LocTy Loc;
4024 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004025 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004026 if (ParseTypeAndValue(Op, Loc, PFS) ||
4027 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4028 ParseType(DestTy))
4029 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004030
Chris Lattner89d856e2009-03-01 00:53:13 +00004031 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4032 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004033 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004034 getTypeString(Op->getType()) + "' to '" +
4035 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004036 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004037 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4038 return false;
4039}
4040
4041/// ParseSelect
4042/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4043bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4044 LocTy Loc;
4045 Value *Op0, *Op1, *Op2;
4046 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4047 ParseToken(lltok::comma, "expected ',' after select condition") ||
4048 ParseTypeAndValue(Op1, PFS) ||
4049 ParseToken(lltok::comma, "expected ',' after select value") ||
4050 ParseTypeAndValue(Op2, PFS))
4051 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004052
Chris Lattnerac161bf2009-01-02 07:01:27 +00004053 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4054 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004055
Chris Lattnerac161bf2009-01-02 07:01:27 +00004056 Inst = SelectInst::Create(Op0, Op1, Op2);
4057 return false;
4058}
4059
Chris Lattnerb55ab542009-01-05 08:18:44 +00004060/// ParseVA_Arg
4061/// ::= 'va_arg' TypeAndValue ',' Type
4062bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004063 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004064 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00004065 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004066 if (ParseTypeAndValue(Op, PFS) ||
4067 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00004068 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004069 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004070
Chris Lattnerb55ab542009-01-05 08:18:44 +00004071 if (!EltTy->isFirstClassType())
4072 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004073
4074 Inst = new VAArgInst(Op, EltTy);
4075 return false;
4076}
4077
4078/// ParseExtractElement
4079/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4080bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4081 LocTy Loc;
4082 Value *Op0, *Op1;
4083 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4084 ParseToken(lltok::comma, "expected ',' after extract value") ||
4085 ParseTypeAndValue(Op1, PFS))
4086 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004087
Chris Lattnerac161bf2009-01-02 07:01:27 +00004088 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4089 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004090
Eric Christopherc9742252009-07-25 02:28:41 +00004091 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004092 return false;
4093}
4094
4095/// ParseInsertElement
4096/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4097bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4098 LocTy Loc;
4099 Value *Op0, *Op1, *Op2;
4100 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4101 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4102 ParseTypeAndValue(Op1, PFS) ||
4103 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4104 ParseTypeAndValue(Op2, PFS))
4105 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004106
Chris Lattnerac161bf2009-01-02 07:01:27 +00004107 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00004108 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004109
Chris Lattnerac161bf2009-01-02 07:01:27 +00004110 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4111 return false;
4112}
4113
4114/// ParseShuffleVector
4115/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4116bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4117 LocTy Loc;
4118 Value *Op0, *Op1, *Op2;
4119 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4120 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4121 ParseTypeAndValue(Op1, PFS) ||
4122 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4123 ParseTypeAndValue(Op2, PFS))
4124 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004125
Chris Lattnerac161bf2009-01-02 07:01:27 +00004126 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00004127 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004128
Chris Lattnerac161bf2009-01-02 07:01:27 +00004129 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4130 return false;
4131}
4132
4133/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00004134/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004135int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004136 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004137 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004138
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004139 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004140 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4141 ParseValue(Ty, Op0, PFS) ||
4142 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004143 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004144 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4145 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004146
Chris Lattnerf4f03422009-12-30 05:27:33 +00004147 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004148 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4149 while (1) {
4150 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004151
Chris Lattner3822f632009-01-02 08:05:26 +00004152 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004153 break;
4154
Chris Lattnerf4f03422009-12-30 05:27:33 +00004155 if (Lex.getKind() == lltok::MetadataVar) {
4156 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00004157 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004158 }
Devang Patel8f842d32009-10-16 18:45:49 +00004159
Chris Lattner3822f632009-01-02 08:05:26 +00004160 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004161 ParseValue(Ty, Op0, PFS) ||
4162 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00004163 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004164 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4165 return true;
4166 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004167
Chris Lattnerac161bf2009-01-02 07:01:27 +00004168 if (!Ty->isFirstClassType())
4169 return Error(TypeLoc, "phi node must have first class type");
4170
Jay Foad52131342011-03-30 11:28:46 +00004171 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004172 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4173 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4174 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004175 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004176}
4177
Bill Wendlingfae14752011-08-12 20:24:12 +00004178/// ParseLandingPad
4179/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4180/// Clause
4181/// ::= 'catch' TypeAndValue
4182/// ::= 'filter'
4183/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4184bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004185 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004186 Value *PersFn; LocTy PersFnLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004187
4188 if (ParseType(Ty, TyLoc) ||
4189 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4190 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4191 return true;
4192
4193 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4194 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4195
4196 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4197 LandingPadInst::ClauseType CT;
4198 if (EatIfPresent(lltok::kw_catch))
4199 CT = LandingPadInst::Catch;
4200 else if (EatIfPresent(lltok::kw_filter))
4201 CT = LandingPadInst::Filter;
4202 else
4203 return TokError("expected 'catch' or 'filter' clause type");
4204
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004205 Value *V;
4206 LocTy VLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00004207 if (ParseTypeAndValue(V, VLoc, PFS)) {
4208 delete LP;
4209 return true;
4210 }
4211
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00004212 // A 'catch' type expects a non-array constant. A filter clause expects an
4213 // array constant.
4214 if (CT == LandingPadInst::Catch) {
4215 if (isa<ArrayType>(V->getType()))
4216 Error(VLoc, "'catch' clause has an invalid type");
4217 } else {
4218 if (!isa<ArrayType>(V->getType()))
4219 Error(VLoc, "'filter' clause has an invalid type");
4220 }
4221
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004222 LP->addClause(cast<Constant>(V));
Bill Wendlingfae14752011-08-12 20:24:12 +00004223 }
4224
4225 Inst = LP;
4226 return false;
4227}
4228
Chris Lattnerac161bf2009-01-02 07:01:27 +00004229/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00004230/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4231/// ParameterList OptionalAttrs
4232/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4233/// ParameterList OptionalAttrs
4234/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004235/// ParameterList OptionalAttrs
4236bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00004237 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00004238 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004239 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004240 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004241 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004242 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004243 LocTy RetTypeLoc;
4244 ValID CalleeID;
4245 SmallVector<ParamInfo, 16> ArgList;
4246 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004247
Reid Kleckner5772b772014-04-24 20:14:34 +00004248 if ((TCK != CallInst::TCK_None &&
4249 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004250 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004251 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004252 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004253 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00004254 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4255 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004256 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004257 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004258 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004259
Chris Lattnerac161bf2009-01-02 07:01:27 +00004260 // If RetType is a non-function pointer type, then this is the short syntax
4261 // for the call, which means that RetType is just the return type. Infer the
4262 // rest of the function argument types from the arguments that are present.
Craig Topper2617dcc2014-04-15 06:32:26 +00004263 PointerType *PFTy = nullptr;
4264 FunctionType *Ty = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004265 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4266 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4267 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004268 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00004269 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4270 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004271
Chris Lattnerac161bf2009-01-02 07:01:27 +00004272 if (!FunctionType::isValidReturnType(RetType))
4273 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004274
Owen Anderson4056ca92009-07-29 22:17:13 +00004275 Ty = FunctionType::get(RetType, ParamTypes, false);
4276 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004277 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004278
Chris Lattnerac161bf2009-01-02 07:01:27 +00004279 // Look up the callee.
4280 Value *Callee;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004281 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004282
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004283 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004284 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004285 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004286 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4287 AttributeSet::ReturnIndex,
4288 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004289
Chris Lattnerac161bf2009-01-02 07:01:27 +00004290 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004291
Chris Lattnerac161bf2009-01-02 07:01:27 +00004292 // Loop through FunctionType's arguments and ensure they are specified
4293 // correctly. Also, gather any parameter attributes.
4294 FunctionType::param_iterator I = Ty->param_begin();
4295 FunctionType::param_iterator E = Ty->param_end();
4296 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004297 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004298 if (I != E) {
4299 ExpectedTy = *I++;
4300 } else if (!Ty->isVarArg()) {
4301 return Error(ArgList[i].Loc, "too many arguments specified");
4302 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004303
Chris Lattnerac161bf2009-01-02 07:01:27 +00004304 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4305 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004306 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004307 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004308 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4309 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004310 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4311 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004312 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004313
Chris Lattnerac161bf2009-01-02 07:01:27 +00004314 if (I != E)
4315 return Error(CallLoc, "not enough parameters specified for call");
4316
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004317 if (FnAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004318 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4319 AttributeSet::FunctionIndex,
4320 FnAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004321
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004322 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004323 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004324
Jay Foad5bd375a2011-07-15 08:37:34 +00004325 CallInst *CI = CallInst::Create(Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00004326 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004327 CI->setCallingConv(CC);
4328 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004329 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004330 Inst = CI;
4331 return false;
4332}
4333
4334//===----------------------------------------------------------------------===//
4335// Memory Instructions.
4336//===----------------------------------------------------------------------===//
4337
4338/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00004339/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00004340int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004341 Value *Size = nullptr;
Chris Lattner200e0752009-07-02 23:08:13 +00004342 LocTy SizeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004343 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004344 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00004345
4346 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4347
Chris Lattner3822f632009-01-02 08:05:26 +00004348 if (ParseType(Ty)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004349
Chris Lattnerb2f39502009-12-30 05:44:30 +00004350 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004351 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00004352 if (Lex.getKind() == lltok::kw_align) {
4353 if (ParseOptionalAlignment(Alignment)) return true;
4354 } else if (Lex.getKind() == lltok::MetadataVar) {
4355 AteExtraComma = true;
4356 } else {
4357 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4358 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4359 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004360 }
4361 }
4362
Dan Gohman2140a742010-05-28 01:14:11 +00004363 if (Size && !Size->getType()->isIntegerTy())
4364 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004365
Reid Kleckner436c42e2014-01-17 23:58:17 +00004366 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4367 AI->setUsedWithInAlloca(IsInAlloca);
4368 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00004369 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004370}
4371
4372/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00004373/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004374/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00004375/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004376int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004377 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004378 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004379 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004380 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004381 AtomicOrdering Ordering = NotAtomic;
4382 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004383
4384 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004385 isAtomic = true;
4386 Lex.Lex();
4387 }
4388
Chris Lattnerbc639292011-11-27 06:56:53 +00004389 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004390 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004391 isVolatile = true;
4392 Lex.Lex();
4393 }
4394
Chris Lattnerb2f39502009-12-30 05:44:30 +00004395 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004396 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004397 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4398 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004399
Duncan Sands19d0b472010-02-16 11:11:14 +00004400 if (!Val->getType()->isPointerTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004401 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4402 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00004403 if (isAtomic && !Alignment)
4404 return Error(Loc, "atomic load must have explicit non-zero alignment");
4405 if (Ordering == Release || Ordering == AcquireRelease)
4406 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004407
Eli Friedman59b66882011-08-09 23:02:53 +00004408 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004409 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004410}
4411
4412/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00004413
4414/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4415/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00004416/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00004417int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004418 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00004419 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00004420 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004421 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00004422 AtomicOrdering Ordering = NotAtomic;
4423 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004424
4425 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004426 isAtomic = true;
4427 Lex.Lex();
4428 }
4429
Chris Lattnerbc639292011-11-27 06:56:53 +00004430 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00004431 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00004432 isVolatile = true;
4433 Lex.Lex();
4434 }
4435
Chris Lattnerac161bf2009-01-02 07:01:27 +00004436 if (ParseTypeAndValue(Val, Loc, PFS) ||
4437 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004438 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00004439 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00004440 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004441 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00004442
Duncan Sands19d0b472010-02-16 11:11:14 +00004443 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004444 return Error(PtrLoc, "store operand must be a pointer");
4445 if (!Val->getType()->isFirstClassType())
4446 return Error(Loc, "store operand must be a first class value");
4447 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4448 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00004449 if (isAtomic && !Alignment)
4450 return Error(Loc, "atomic store must have explicit non-zero alignment");
4451 if (Ordering == Acquire || Ordering == AcquireRelease)
4452 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004453
Eli Friedman59b66882011-08-09 23:02:53 +00004454 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00004455 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004456}
4457
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004458/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00004459/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4460/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00004461int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004462 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4463 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00004464 AtomicOrdering SuccessOrdering = NotAtomic;
4465 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004466 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004467 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00004468 bool isWeak = false;
4469
4470 if (EatIfPresent(lltok::kw_weak))
4471 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00004472
4473 if (EatIfPresent(lltok::kw_volatile))
4474 isVolatile = true;
4475
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004476 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4477 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4478 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4479 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4480 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00004481 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4482 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004483 return true;
4484
Tim Northovere94a5182014-03-11 10:48:52 +00004485 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004486 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00004487 if (SuccessOrdering < FailureOrdering)
4488 return TokError("cmpxchg must be at least as ordered on success as failure");
4489 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4490 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004491 if (!Ptr->getType()->isPointerTy())
4492 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4493 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4494 return Error(CmpLoc, "compare value and pointer type do not match");
4495 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4496 return Error(NewLoc, "new value and pointer type do not match");
4497 if (!New->getType()->isIntegerTy())
4498 return Error(NewLoc, "cmpxchg operand must be an integer");
4499 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4500 if (Size < 8 || (Size & (Size - 1)))
4501 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4502 " integer");
4503
Tim Northover420a2162014-06-13 14:24:07 +00004504 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4505 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004506 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00004507 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004508 Inst = CXI;
4509 return AteExtraComma ? InstExtraComma : InstNormal;
4510}
4511
4512/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00004513/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4514/// 'singlethread'? AtomicOrdering
4515int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004516 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4517 bool AteExtraComma = false;
4518 AtomicOrdering Ordering = NotAtomic;
4519 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00004520 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004521 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00004522
4523 if (EatIfPresent(lltok::kw_volatile))
4524 isVolatile = true;
4525
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004526 switch (Lex.getKind()) {
4527 default: return TokError("expected binary operation in atomicrmw");
4528 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4529 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4530 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4531 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4532 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4533 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4534 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4535 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4536 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4537 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4538 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4539 }
4540 Lex.Lex(); // Eat the operation.
4541
4542 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4543 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4544 ParseTypeAndValue(Val, ValLoc, PFS) ||
4545 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4546 return true;
4547
4548 if (Ordering == Unordered)
4549 return TokError("atomicrmw cannot be unordered");
4550 if (!Ptr->getType()->isPointerTy())
4551 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4552 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4553 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4554 if (!Val->getType()->isIntegerTy())
4555 return Error(ValLoc, "atomicrmw operand must be an integer");
4556 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4557 if (Size < 8 || (Size & (Size - 1)))
4558 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4559 " integer");
4560
4561 AtomicRMWInst *RMWI =
4562 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4563 RMWI->setVolatile(isVolatile);
4564 Inst = RMWI;
4565 return AteExtraComma ? InstExtraComma : InstNormal;
4566}
4567
Eli Friedmanfee02c62011-07-25 23:16:38 +00004568/// ParseFence
4569/// ::= 'fence' 'singlethread'? AtomicOrdering
4570int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4571 AtomicOrdering Ordering = NotAtomic;
4572 SynchronizationScope Scope = CrossThread;
4573 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4574 return true;
4575
4576 if (Ordering == Unordered)
4577 return TokError("fence cannot be unordered");
4578 if (Ordering == Monotonic)
4579 return TokError("fence cannot be monotonic");
4580
4581 Inst = new FenceInst(Context, Ordering, Scope);
4582 return InstNormal;
4583}
4584
Chris Lattnerac161bf2009-01-02 07:01:27 +00004585/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00004586/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00004587int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004588 Value *Ptr = nullptr;
4589 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004590 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00004591
Dan Gohman16cbbe42009-07-29 15:58:36 +00004592 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00004593
Chris Lattner3822f632009-01-02 08:05:26 +00004594 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004595
Eli Benderskyd9806682013-04-22 17:03:42 +00004596 Type *BaseType = Ptr->getType();
4597 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4598 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004599 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004600
Chris Lattnerac161bf2009-01-02 07:01:27 +00004601 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004602 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00004603 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00004604 if (Lex.getKind() == lltok::MetadataVar) {
4605 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00004606 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004607 }
Chris Lattner3822f632009-01-02 08:05:26 +00004608 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00004609 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004610 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00004611 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4612 return Error(EltLoc, "getelementptr index type missmatch");
4613 if (Val->getType()->isVectorTy()) {
4614 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4615 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4616 if (ValNumEl != PtrNumEl)
4617 return Error(EltLoc,
4618 "getelementptr vector index has a wrong number of elements");
4619 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004620 Indices.push_back(Val);
4621 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004622
Eli Benderskyd9806682013-04-22 17:03:42 +00004623 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4624 return Error(Loc, "base element of getelementptr must be sized");
4625
4626 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004627 return Error(Loc, "invalid getelementptr indices");
Jay Foadd1b78492011-07-25 09:48:08 +00004628 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00004629 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004630 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004631 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004632}
4633
4634/// ParseExtractValue
4635/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004636int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004637 Value *Val; LocTy Loc;
4638 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004639 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004640 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004641 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004642 return true;
4643
Chris Lattner392be582010-02-12 20:49:41 +00004644 if (!Val->getType()->isAggregateType())
4645 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004646
Jay Foad57aa6362011-07-13 10:26:04 +00004647 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004648 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004649 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004650 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004651}
4652
4653/// ParseInsertValue
4654/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00004655int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004656 Value *Val0, *Val1; LocTy Loc0, Loc1;
4657 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00004658 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004659 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4660 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4661 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00004662 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004663 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004664
Chris Lattner392be582010-02-12 20:49:41 +00004665 if (!Val0->getType()->isAggregateType())
4666 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004667
Jay Foad57aa6362011-07-13 10:26:04 +00004668 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004669 return Error(Loc0, "invalid indices for insertvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00004670 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00004671 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004672}
Nick Lewycky49f89192009-04-04 07:22:01 +00004673
4674//===----------------------------------------------------------------------===//
4675// Embedded metadata.
4676//===----------------------------------------------------------------------===//
4677
4678/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004679/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004680/// Element
4681/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004682bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00004683 if (ParseToken(lltok::lbrace, "expected '{' here"))
4684 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004685
Dan Gohman1e0213a2010-07-13 19:33:27 +00004686 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004687 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00004688 return false;
4689
Nick Lewycky49f89192009-04-04 07:22:01 +00004690 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004691 // Null is a special case since it is typeless.
4692 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004693 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00004694 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00004695 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004696
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004697 Metadata *MD;
4698 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004699 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004700 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00004701 } while (EatIfPresent(lltok::comma));
4702
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004703 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00004704}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004705
4706//===----------------------------------------------------------------------===//
4707// Use-list order directives.
4708//===----------------------------------------------------------------------===//
4709bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4710 SMLoc Loc) {
4711 if (V->use_empty())
4712 return Error(Loc, "value has no uses");
4713
4714 unsigned NumUses = 0;
4715 SmallDenseMap<const Use *, unsigned, 16> Order;
4716 for (const Use &U : V->uses()) {
4717 if (++NumUses > Indexes.size())
4718 break;
4719 Order[&U] = Indexes[NumUses - 1];
4720 }
4721 if (NumUses < 2)
4722 return Error(Loc, "value only has one use");
4723 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4724 return Error(Loc, "wrong number of indexes, expected " +
4725 Twine(std::distance(V->use_begin(), V->use_end())));
4726
4727 V->sortUseList([&](const Use &L, const Use &R) {
4728 return Order.lookup(&L) < Order.lookup(&R);
4729 });
4730 return false;
4731}
4732
4733/// ParseUseListOrderIndexes
4734/// ::= '{' uint32 (',' uint32)+ '}'
4735bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4736 SMLoc Loc = Lex.getLoc();
4737 if (ParseToken(lltok::lbrace, "expected '{' here"))
4738 return true;
4739 if (Lex.getKind() == lltok::rbrace)
4740 return Lex.Error("expected non-empty list of uselistorder indexes");
4741
4742 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4743 // indexes should be distinct numbers in the range [0, size-1], and should
4744 // not be in order.
4745 unsigned Offset = 0;
4746 unsigned Max = 0;
4747 bool IsOrdered = true;
4748 assert(Indexes.empty() && "Expected empty order vector");
4749 do {
4750 unsigned Index;
4751 if (ParseUInt32(Index))
4752 return true;
4753
4754 // Update consistency checks.
4755 Offset += Index - Indexes.size();
4756 Max = std::max(Max, Index);
4757 IsOrdered &= Index == Indexes.size();
4758
4759 Indexes.push_back(Index);
4760 } while (EatIfPresent(lltok::comma));
4761
4762 if (ParseToken(lltok::rbrace, "expected '}' here"))
4763 return true;
4764
4765 if (Indexes.size() < 2)
4766 return Error(Loc, "expected >= 2 uselistorder indexes");
4767 if (Offset != 0 || Max >= Indexes.size())
4768 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4769 if (IsOrdered)
4770 return Error(Loc, "expected uselistorder indexes to change the order");
4771
4772 return false;
4773}
4774
4775/// ParseUseListOrder
4776/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4777bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4778 SMLoc Loc = Lex.getLoc();
4779 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
4780 return true;
4781
4782 Value *V;
4783 SmallVector<unsigned, 16> Indexes;
4784 if (ParseTypeAndValue(V, PFS) ||
4785 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
4786 ParseUseListOrderIndexes(Indexes))
4787 return true;
4788
4789 return sortUseListOrder(V, Indexes, Loc);
4790}
4791
4792/// ParseUseListOrderBB
4793/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
4794bool LLParser::ParseUseListOrderBB() {
4795 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
4796 SMLoc Loc = Lex.getLoc();
4797 Lex.Lex();
4798
4799 ValID Fn, Label;
4800 SmallVector<unsigned, 16> Indexes;
4801 if (ParseValID(Fn) ||
4802 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4803 ParseValID(Label) ||
4804 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4805 ParseUseListOrderIndexes(Indexes))
4806 return true;
4807
4808 // Check the function.
4809 GlobalValue *GV;
4810 if (Fn.Kind == ValID::t_GlobalName)
4811 GV = M->getNamedValue(Fn.StrVal);
4812 else if (Fn.Kind == ValID::t_GlobalID)
4813 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
4814 else
4815 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4816 if (!GV)
4817 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
4818 auto *F = dyn_cast<Function>(GV);
4819 if (!F)
4820 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4821 if (F->isDeclaration())
4822 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
4823
4824 // Check the basic block.
4825 if (Label.Kind == ValID::t_LocalID)
4826 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
4827 if (Label.Kind != ValID::t_LocalName)
4828 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
4829 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
4830 if (!V)
4831 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
4832 if (!isa<BasicBlock>(V))
4833 return Error(Label.Loc, "expected basic block in uselistorder_bb");
4834
4835 return sortUseListOrder(V, Indexes, Loc);
4836}