blob: 74cf5665924280858fb514776d6d19220f71a725 [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"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000016#include "llvm/AsmParser/SlotMapping.h"
Chandler Carruth91065212014-03-05 10:34:14 +000017#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/CallingConv.h"
19#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +000020#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000021#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DerivedTypes.h"
23#include "llvm/IR/InlineAsm.h"
24#include "llvm/IR/Instructions.h"
Manman Ren209b17c2013-09-28 00:22:27 +000025#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
27#include "llvm/IR/Operator.h"
28#include "llvm/IR/ValueSymbolTable.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000029#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000031#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000032#include "llvm/Support/raw_ostream.h"
33using namespace llvm;
34
Chris Lattner229907c2011-07-18 04:54:35 +000035static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000036 std::string Result;
37 raw_string_ostream Tmp(Result);
38 Tmp << *T;
39 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000040}
41
Chris Lattner3822f632009-01-02 08:05:26 +000042/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000043bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000044 // Prime the lexer.
45 Lex.Lex();
46
Chris Lattnerad6f3352009-01-04 20:44:11 +000047 return ParseTopLevelEntities() ||
48 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000049}
50
Alex Lorenzd2255952015-07-17 22:07:03 +000051bool LLParser::parseStandaloneConstantValue(Constant *&C) {
52 Lex.Lex();
53
54 Type *Ty = nullptr;
55 if (ParseType(Ty) || parseConstantValue(Ty, C))
56 return true;
57 if (Lex.getKind() != lltok::Eof)
58 return Error(Lex.getLoc(), "expected end of string");
59 return false;
60}
61
Chris Lattnerac161bf2009-01-02 07:01:27 +000062/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
63/// module.
64bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000065 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
66 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
67
Bill Wendlingb32b0412013-02-08 06:32:06 +000068 // Handle any function attribute group forward references.
69 for (std::map<Value*, std::vector<unsigned> >::iterator
70 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
71 I != E; ++I) {
72 Value *V = I->first;
73 std::vector<unsigned> &Vec = I->second;
74 AttrBuilder B;
75
76 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
77 VI != VE; ++VI)
78 B.merge(NumberedAttrBuilders[*VI]);
79
80 if (Function *Fn = dyn_cast<Function>(V)) {
81 AttributeSet AS = Fn->getAttributes();
82 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
83 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
84 AS.getFnAttributes());
85
86 FnAttrs.merge(B);
87
88 // If the alignment was parsed as an attribute, move to the alignment
89 // field.
90 if (FnAttrs.hasAlignmentAttr()) {
91 Fn->setAlignment(FnAttrs.getAlignment());
92 FnAttrs.removeAttribute(Attribute::Alignment);
93 }
94
95 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
96 AttributeSet::get(Context,
97 AttributeSet::FunctionIndex,
98 FnAttrs));
99 Fn->setAttributes(AS);
100 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
101 AttributeSet AS = CI->getAttributes();
102 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
103 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
104 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000105 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000106 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
107 AttributeSet::get(Context,
108 AttributeSet::FunctionIndex,
109 FnAttrs));
110 CI->setAttributes(AS);
111 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
112 AttributeSet AS = II->getAttributes();
113 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
114 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
115 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000116 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000117 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
118 AttributeSet::get(Context,
119 AttributeSet::FunctionIndex,
120 FnAttrs));
121 II->setAttributes(AS);
122 } else {
123 llvm_unreachable("invalid object with forward attribute group reference");
124 }
125 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000126
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000127 // If there are entries in ForwardRefBlockAddresses at this point, the
128 // function was never defined.
129 if (!ForwardRefBlockAddresses.empty())
130 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
131 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000132
David Majnemer19b51052015-02-11 07:43:56 +0000133 for (const auto &NT : NumberedTypes)
134 if (NT.second.second.isValid())
135 return Error(NT.second.second,
136 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000137
138 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
139 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
140 if (I->second.second.isValid())
141 return Error(I->second.second,
142 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000143
David Majnemerdad0a642014-06-27 18:19:56 +0000144 if (!ForwardRefComdats.empty())
145 return Error(ForwardRefComdats.begin()->second,
146 "use of undefined comdat '$" +
147 ForwardRefComdats.begin()->first + "'");
148
Chris Lattnerac161bf2009-01-02 07:01:27 +0000149 if (!ForwardRefVals.empty())
150 return Error(ForwardRefVals.begin()->second.second,
151 "use of undefined value '@" + ForwardRefVals.begin()->first +
152 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000153
Chris Lattnerac161bf2009-01-02 07:01:27 +0000154 if (!ForwardRefValIDs.empty())
155 return Error(ForwardRefValIDs.begin()->second.second,
156 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000157 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000158
Devang Pateld2541152009-07-08 19:23:54 +0000159 if (!ForwardRefMDNodes.empty())
160 return Error(ForwardRefMDNodes.begin()->second.second,
161 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000162 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000163
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000164 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000165 for (auto &N : NumberedMetadata) {
166 if (N.second && !N.second->isResolved())
167 N.second->resolveCycles();
168 }
Devang Pateld2541152009-07-08 19:23:54 +0000169
Chris Lattnerac161bf2009-01-02 07:01:27 +0000170 // Look for intrinsic functions and CallInst that need to be upgraded
171 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
172 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000173
Manman Ren8b4306c2013-12-02 21:29:56 +0000174 UpgradeDebugInfo(*M);
175
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000176 if (!Slots)
177 return false;
178 // Initialize the slot mapping.
179 // Because by this point we've parsed and validated everything, we can "steal"
180 // the mapping from LLParser as it doesn't need it anymore.
181 Slots->GlobalValues = std::move(NumberedVals);
182 Slots->MetadataNodes = std::move(NumberedMetadata);
183
Chris Lattnerac161bf2009-01-02 07:01:27 +0000184 return false;
185}
186
187//===----------------------------------------------------------------------===//
188// Top-Level Entities
189//===----------------------------------------------------------------------===//
190
191bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000192 while (1) {
193 switch (Lex.getKind()) {
194 default: return TokError("expected top-level entity");
195 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000196 case lltok::kw_declare: if (ParseDeclare()) return true; break;
197 case lltok::kw_define: if (ParseDefine()) return true; break;
198 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
199 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000200 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000201 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000202 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000203 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000204 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000205 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000206 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000207 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000208
209 // The Global variable production with no name can have many different
210 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000211 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000212 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000213 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000214 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000215 case lltok::kw_internal: // OptionalLinkage
216 case lltok::kw_weak: // OptionalLinkage
217 case lltok::kw_weak_odr: // OptionalLinkage
218 case lltok::kw_linkonce: // OptionalLinkage
219 case lltok::kw_linkonce_odr: // OptionalLinkage
220 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000221 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000222 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000223 case lltok::kw_external: // OptionalLinkage
224 case lltok::kw_default: // OptionalVisibility
225 case lltok::kw_hidden: // OptionalVisibility
226 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000227 case lltok::kw_dllimport: // OptionalDLLStorageClass
228 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000229 case lltok::kw_thread_local: // OptionalThreadLocal
230 case lltok::kw_addrspace: // OptionalAddrSpace
231 case lltok::kw_constant: // GlobalType
232 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000233 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000234 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000235 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000236 bool HasLinkage;
237 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000238 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000239 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000240 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000241 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000242 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000243 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000244 return true;
245 break;
246 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000247
248 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000249 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
250 case lltok::kw_uselistorder_bb:
251 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000252 }
253 }
254}
255
256
257/// toplevelentity
258/// ::= 'module' 'asm' STRINGCONSTANT
259bool LLParser::ParseModuleAsm() {
260 assert(Lex.getKind() == lltok::kw_module);
261 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000262
263 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000264 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
265 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000266
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000267 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000268 return false;
269}
270
271/// toplevelentity
272/// ::= 'target' 'triple' '=' STRINGCONSTANT
273/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
274bool LLParser::ParseTargetDefinition() {
275 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000276 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000277 switch (Lex.Lex()) {
278 default: return TokError("unknown target property");
279 case lltok::kw_triple:
280 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000281 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
282 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000283 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000284 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000285 return false;
286 case lltok::kw_datalayout:
287 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000288 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
289 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000290 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000291 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000292 return false;
293 }
294}
295
Bill Wendling706d3d62012-11-28 08:41:48 +0000296/// toplevelentity
297/// ::= 'deplibs' '=' '[' ']'
298/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
299/// FIXME: Remove in 4.0. Currently parse, but ignore.
300bool LLParser::ParseDepLibs() {
301 assert(Lex.getKind() == lltok::kw_deplibs);
302 Lex.Lex();
303 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
304 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
305 return true;
306
307 if (EatIfPresent(lltok::rsquare))
308 return false;
309
310 do {
311 std::string Str;
312 if (ParseStringConstant(Str)) return true;
313 } while (EatIfPresent(lltok::comma));
314
315 return ParseToken(lltok::rsquare, "expected ']' at end of list");
316}
317
Dan Gohman466876b2009-08-12 23:32:33 +0000318/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000319/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000320bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000321 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000322 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000323 Lex.Lex(); // eat LocalVarID;
324
325 if (ParseToken(lltok::equal, "expected '=' after name") ||
326 ParseToken(lltok::kw_type, "expected 'type' after '='"))
327 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000328
Craig Topper2617dcc2014-04-15 06:32:26 +0000329 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000330 if (ParseStructDefinition(TypeLoc, "",
331 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000332
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000333 if (!isa<StructType>(Result)) {
334 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
335 if (Entry.first)
336 return Error(TypeLoc, "non-struct types may not be recursive");
337 Entry.first = Result;
338 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000339 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000340
Chris Lattnerac161bf2009-01-02 07:01:27 +0000341 return false;
342}
343
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000344
Chris Lattnerac161bf2009-01-02 07:01:27 +0000345/// toplevelentity
346/// ::= LocalVar '=' 'type' type
347bool LLParser::ParseNamedType() {
348 std::string Name = Lex.getStrVal();
349 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000350 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000351
Chris Lattner3822f632009-01-02 08:05:26 +0000352 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000353 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000354 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000355
Craig Topper2617dcc2014-04-15 06:32:26 +0000356 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000357 if (ParseStructDefinition(NameLoc, Name,
358 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000359
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000360 if (!isa<StructType>(Result)) {
361 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
362 if (Entry.first)
363 return Error(NameLoc, "non-struct types may not be recursive");
364 Entry.first = Result;
365 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000366 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000367
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000368 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000369}
370
371
372/// toplevelentity
373/// ::= 'declare' FunctionHeader
374bool LLParser::ParseDeclare() {
375 assert(Lex.getKind() == lltok::kw_declare);
376 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000377
Chris Lattnerac161bf2009-01-02 07:01:27 +0000378 Function *F;
379 return ParseFunctionHeader(F, false);
380}
381
382/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000383/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000384bool LLParser::ParseDefine() {
385 assert(Lex.getKind() == lltok::kw_define);
386 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000387
Chris Lattnerac161bf2009-01-02 07:01:27 +0000388 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000389 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000390 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000391 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000392}
393
Chris Lattner3822f632009-01-02 08:05:26 +0000394/// ParseGlobalType
395/// ::= 'constant'
396/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000397bool LLParser::ParseGlobalType(bool &IsConstant) {
398 if (Lex.getKind() == lltok::kw_constant)
399 IsConstant = true;
400 else if (Lex.getKind() == lltok::kw_global)
401 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000402 else {
403 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000404 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000405 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000406 Lex.Lex();
407 return false;
408}
409
Dan Gohman466876b2009-08-12 23:32:33 +0000410/// ParseUnnamedGlobal:
411/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000412/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
413/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000414/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000415/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
416/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000417bool LLParser::ParseUnnamedGlobal() {
418 unsigned VarID = NumberedVals.size();
419 std::string Name;
420 LocTy NameLoc = Lex.getLoc();
421
422 // Handle the GlobalID form.
423 if (Lex.getKind() == lltok::GlobalID) {
424 if (Lex.getUIntVal() != VarID)
425 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000426 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000427 Lex.Lex(); // eat GlobalID;
428
429 if (ParseToken(lltok::equal, "expected '=' after name"))
430 return true;
431 }
432
433 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000434 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000435 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000436 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000437 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000438 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000439 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000440 ParseOptionalThreadLocal(TLM) ||
441 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000442 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000443
Rafael Espindola464fe022014-07-30 22:51:54 +0000444 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000445 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000446 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000447 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000448 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000449}
450
Chris Lattnerac161bf2009-01-02 07:01:27 +0000451/// ParseNamedGlobal:
452/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000453/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
454/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000455bool LLParser::ParseNamedGlobal() {
456 assert(Lex.getKind() == lltok::GlobalVar);
457 LocTy NameLoc = Lex.getLoc();
458 std::string Name = Lex.getStrVal();
459 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000460
Chris Lattnerac161bf2009-01-02 07:01:27 +0000461 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000462 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000463 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000464 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000465 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
466 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000467 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000468 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000469 ParseOptionalThreadLocal(TLM) ||
470 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000471 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000472
Rafael Espindola464fe022014-07-30 22:51:54 +0000473 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000474 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000475 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000476
477 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000478 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000479}
480
David Majnemerdad0a642014-06-27 18:19:56 +0000481bool LLParser::parseComdat() {
482 assert(Lex.getKind() == lltok::ComdatVar);
483 std::string Name = Lex.getStrVal();
484 LocTy NameLoc = Lex.getLoc();
485 Lex.Lex();
486
487 if (ParseToken(lltok::equal, "expected '=' here"))
488 return true;
489
490 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
491 return TokError("expected comdat type");
492
493 Comdat::SelectionKind SK;
494 switch (Lex.getKind()) {
495 default:
496 return TokError("unknown selection kind");
497 case lltok::kw_any:
498 SK = Comdat::Any;
499 break;
500 case lltok::kw_exactmatch:
501 SK = Comdat::ExactMatch;
502 break;
503 case lltok::kw_largest:
504 SK = Comdat::Largest;
505 break;
506 case lltok::kw_noduplicates:
507 SK = Comdat::NoDuplicates;
508 break;
509 case lltok::kw_samesize:
510 SK = Comdat::SameSize;
511 break;
512 }
513 Lex.Lex();
514
515 // See if the comdat was forward referenced, if so, use the comdat.
516 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
517 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
518 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
519 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
520
521 Comdat *C;
522 if (I != ComdatSymTab.end())
523 C = &I->second;
524 else
525 C = M->getOrInsertComdat(Name);
526 C->setSelectionKind(SK);
527
528 return false;
529}
530
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000531// MDString:
532// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000533bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000534 std::string Str;
535 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000536 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000537 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000538 return false;
539}
540
541// MDNode:
542// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000543bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000544 // !{ ..., !42, ... }
545 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000546 if (ParseUInt32(MID))
547 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000548
Chris Lattner8eff0152010-04-01 05:14:45 +0000549 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000550 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000551 Result = NumberedMetadata[MID];
552 return false;
553 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000554
Chris Lattner8eff0152010-04-01 05:14:45 +0000555 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000556 auto &FwdRef = ForwardRefMDNodes[MID];
557 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000558
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000559 Result = FwdRef.first.get();
560 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000561 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000562}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000563
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000564/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000565/// !foo = !{ !1, !2 }
566bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000567 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000568 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000569 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000570
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000571 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000572 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000573 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000574 return true;
575
Dan Gohman2637cc12010-07-21 23:38:33 +0000576 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000577 if (Lex.getKind() != lltok::rbrace)
578 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000579 if (ParseToken(lltok::exclaim, "Expected '!' here"))
580 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000581
Craig Topper2617dcc2014-04-15 06:32:26 +0000582 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000583 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000584 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000585 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000586
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000587 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000588}
589
Devang Patel39e64d42009-07-01 19:21:12 +0000590/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000591/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000592bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000593 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000594 Lex.Lex();
595 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000596
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000597 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000598 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000599 ParseToken(lltok::equal, "expected '=' here"))
600 return true;
601
602 // Detect common error, from old metadata syntax.
603 if (Lex.getKind() == lltok::Type)
604 return TokError("unexpected type in metadata definition");
605
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000606 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000607 if (Lex.getKind() == lltok::MetadataVar) {
608 if (ParseSpecializedMDNode(Init, IsDistinct))
609 return true;
610 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
611 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000612 return true;
613
Chris Lattnerfc58af22009-12-30 04:51:58 +0000614 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000615 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000616 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000617 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000618 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000619
Chris Lattnerfc58af22009-12-30 04:51:58 +0000620 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
621 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000622 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000623 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000624 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000625 }
626
Devang Patel39e64d42009-07-01 19:21:12 +0000627 return false;
628}
629
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000630static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
631 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
632 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
633}
634
Chris Lattnerac161bf2009-01-02 07:01:27 +0000635/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000636/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
637/// OptionalDLLStorageClass OptionalThreadLocal
Eric Christopher536f0a92015-05-28 23:07:39 +0000638/// OptionalUnnamedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000639///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000640/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000641/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000642///
Eric Christopher536f0a92015-05-28 23:07:39 +0000643/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000644///
Rafael Espindola464fe022014-07-30 22:51:54 +0000645bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000646 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000647 GlobalVariable::ThreadLocalMode TLM,
648 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000649 assert(Lex.getKind() == lltok::kw_alias);
650 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000651
Rafael Espindola78527052013-10-06 15:10:43 +0000652 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
653
Rafael Espindolacaa43562013-10-09 16:07:32 +0000654 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000655 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000656
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000657 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000658 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000659 "symbol with local linkage must have default visibility");
660
Rafael Espindola64c1e182014-06-03 02:41:57 +0000661 Constant *Aliasee;
662 LocTy AliaseeLoc = Lex.getLoc();
663 if (Lex.getKind() != lltok::kw_bitcast &&
664 Lex.getKind() != lltok::kw_getelementptr &&
665 Lex.getKind() != lltok::kw_addrspacecast &&
666 Lex.getKind() != lltok::kw_inttoptr) {
667 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000668 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000669 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000670 // The bitcast dest type is not present, it is implied by the dest type.
671 ValID ID;
672 if (ParseValID(ID))
673 return true;
674 if (ID.Kind != ValID::t_Constant)
675 return Error(AliaseeLoc, "invalid aliasee");
676 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000677 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000678
Rafael Espindola64c1e182014-06-03 02:41:57 +0000679 Type *AliaseeType = Aliasee->getType();
680 auto *PTy = dyn_cast<PointerType>(AliaseeType);
681 if (!PTy)
682 return Error(AliaseeLoc, "An alias must have pointer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000683
684 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000685 std::unique_ptr<GlobalAlias> GA(
David Blaikief64246b2015-04-29 21:22:39 +0000686 GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
687 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000688 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000689 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000690 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000691 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000692
Rafael Espindola54fc2982015-06-17 17:53:31 +0000693 if (Name.empty())
694 NumberedVals.push_back(GA.get());
695
Chris Lattnerac161bf2009-01-02 07:01:27 +0000696 // See if this value already exists in the symbol table. If so, it is either
697 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000698 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000699 // See if this was a redefinition. If so, there is no entry in
700 // ForwardRefVals.
701 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
702 I = ForwardRefVals.find(Name);
703 if (I == ForwardRefVals.end())
704 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
705
706 // Otherwise, this was a definition of forward ref. Verify that types
707 // agree.
708 if (Val->getType() != GA->getType())
709 return Error(NameLoc,
710 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000711
Chris Lattnerac161bf2009-01-02 07:01:27 +0000712 // If they agree, just RAUW the old value with the alias and remove the
713 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000714 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000715 Val->eraseFromParent();
716 ForwardRefVals.erase(I);
717 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000718
Chris Lattnerac161bf2009-01-02 07:01:27 +0000719 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000720 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000721 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000722
Rafael Espindolaaa273822014-05-09 21:49:17 +0000723 // The module owns this now
724 GA.release();
725
Chris Lattnerac161bf2009-01-02 07:01:27 +0000726 return false;
727}
728
729/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000730/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000731/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000732/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000733/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000734/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000735/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000736///
Eric Christopher536f0a92015-05-28 23:07:39 +0000737/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000738/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000739///
740bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
741 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000742 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000743 GlobalVariable::ThreadLocalMode TLM,
744 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000745 if (!isValidVisibilityForLinkage(Visibility, Linkage))
746 return Error(NameLoc,
747 "symbol with local linkage must have default visibility");
748
Chris Lattnerac161bf2009-01-02 07:01:27 +0000749 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000750 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000751 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000752 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000753
Craig Topper2617dcc2014-04-15 06:32:26 +0000754 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000755 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000756 ParseOptionalToken(lltok::kw_externally_initialized,
757 IsExternallyInitialized,
758 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000759 ParseGlobalType(IsConstant) ||
760 ParseType(Ty, TyLoc))
761 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000762
Chris Lattnerac161bf2009-01-02 07:01:27 +0000763 // If the linkage is specified and is external, then no initializer is
764 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000765 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000766 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000767 Linkage != GlobalValue::ExternalLinkage)) {
768 if (ParseGlobalValue(Ty, Init))
769 return true;
770 }
771
David Majnemer49b3d9b2015-02-16 08:41:08 +0000772 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000773 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000774
David Majnemer598bd052014-12-09 05:56:09 +0000775 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000776
777 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000778 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000779 GVal = M->getNamedValue(Name);
780 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000781 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
782 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000783 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000784 } else {
785 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
786 I = ForwardRefValIDs.find(NumberedVals.size());
787 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000788 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000789 ForwardRefValIDs.erase(I);
790 }
791 }
792
David Majnemer598bd052014-12-09 05:56:09 +0000793 GlobalVariable *GV;
794 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000795 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
796 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000797 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000798 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000799 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000800 return Error(TyLoc,
801 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000802
David Majnemer598bd052014-12-09 05:56:09 +0000803 GV = cast<GlobalVariable>(GVal);
804
Chris Lattnerac161bf2009-01-02 07:01:27 +0000805 // Move the forward-reference to the correct spot in the module.
806 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
807 }
808
809 if (Name.empty())
810 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000811
Chris Lattnerac161bf2009-01-02 07:01:27 +0000812 // Set the parsed properties on the global.
813 if (Init)
814 GV->setInitializer(Init);
815 GV->setConstant(IsConstant);
816 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
817 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000818 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000819 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000820 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000821 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000822
Chris Lattnerac161bf2009-01-02 07:01:27 +0000823 // Parse attributes on the global.
824 while (Lex.getKind() == lltok::comma) {
825 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000826
Chris Lattnerac161bf2009-01-02 07:01:27 +0000827 if (Lex.getKind() == lltok::kw_section) {
828 Lex.Lex();
829 GV->setSection(Lex.getStrVal());
830 if (ParseToken(lltok::StringConstant, "expected global section string"))
831 return true;
832 } else if (Lex.getKind() == lltok::kw_align) {
833 unsigned Alignment;
834 if (ParseOptionalAlignment(Alignment)) return true;
835 GV->setAlignment(Alignment);
836 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000837 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000838 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000839 return true;
840 if (C)
841 GV->setComdat(C);
842 else
843 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000844 }
845 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000846
Chris Lattnerac161bf2009-01-02 07:01:27 +0000847 return false;
848}
849
Bill Wendling63b88192013-02-06 06:52:58 +0000850/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000851/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000852bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000853 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000854 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000855 Lex.Lex();
856
David Majnemerb39e22b2014-12-09 18:33:57 +0000857 if (Lex.getKind() != lltok::AttrGrpID)
858 return TokError("expected attribute group id");
859
Bill Wendling63b88192013-02-06 06:52:58 +0000860 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000861 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000862 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000863 Lex.Lex();
864
865 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000866 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000867 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000868 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000869 ParseToken(lltok::rbrace, "expected end of attribute group"))
870 return true;
871
Bill Wendlingb32b0412013-02-08 06:32:06 +0000872 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000873 return Error(AttrGrpLoc, "attribute group has no attributes");
874
875 return false;
876}
877
Bill Wendling8b0321d2013-02-08 00:52:31 +0000878/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000879/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000880bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
881 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000882 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000883 bool HaveError = false;
884
885 B.clear();
886
Bill Wendling63b88192013-02-06 06:52:58 +0000887 while (true) {
888 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000889 if (Token == lltok::kw_builtin)
890 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000891 switch (Token) {
892 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000893 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000894 return Error(Lex.getLoc(), "unterminated attribute group");
895 case lltok::rbrace:
896 // Finished.
897 return false;
898
Bill Wendlingb32b0412013-02-08 06:32:06 +0000899 case lltok::AttrGrpID: {
900 // Allow a function to reference an attribute group:
901 //
902 // define void @foo() #1 { ... }
903 if (inAttrGrp)
904 HaveError |=
905 Error(Lex.getLoc(),
906 "cannot have an attribute group reference in an attribute group");
907
908 unsigned AttrGrpNum = Lex.getUIntVal();
909 if (inAttrGrp) break;
910
911 // Save the reference to the attribute group. We'll fill it in later.
912 FwdRefAttrGrps.push_back(AttrGrpNum);
913 break;
914 }
Bill Wendling63b88192013-02-06 06:52:58 +0000915 // Target-dependent attributes:
916 case lltok::StringConstant: {
917 std::string Attr = Lex.getStrVal();
918 Lex.Lex();
919 std::string Val;
920 if (EatIfPresent(lltok::equal) &&
921 ParseStringConstant(Val))
922 return true;
923
924 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000925 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000926 }
927
928 // Target-independent attributes:
929 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000930 // As a hack, we allow function alignment to be initially parsed as an
931 // attribute on a function declaration/definition or added to an attribute
932 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000933 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000934 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000935 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000936 if (ParseToken(lltok::equal, "expected '=' here") ||
937 ParseUInt32(Alignment))
938 return true;
939 } else {
940 if (ParseOptionalAlignment(Alignment))
941 return true;
942 }
Bill Wendling63b88192013-02-06 06:52:58 +0000943 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000944 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000945 }
946 case lltok::kw_alignstack: {
947 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000948 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000949 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000950 if (ParseToken(lltok::equal, "expected '=' here") ||
951 ParseUInt32(Alignment))
952 return true;
953 } else {
954 if (ParseOptionalStackAlignment(Alignment))
955 return true;
956 }
Bill Wendling63b88192013-02-06 06:52:58 +0000957 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000958 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000959 }
Igor Laevsky39d662f2015-07-11 10:30:36 +0000960 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
961 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
962 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
963 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
964 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
965 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
966 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
967 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
968 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
969 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
970 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
971 case lltok::kw_noimplicitfloat:
972 B.addAttribute(Attribute::NoImplicitFloat); break;
973 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
974 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
975 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
976 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
977 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
978 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
979 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
980 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
981 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
982 case lltok::kw_returns_twice:
983 B.addAttribute(Attribute::ReturnsTwice); break;
984 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
985 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
986 case lltok::kw_sspstrong:
987 B.addAttribute(Attribute::StackProtectStrong); break;
988 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
989 case lltok::kw_sanitize_address:
990 B.addAttribute(Attribute::SanitizeAddress); break;
991 case lltok::kw_sanitize_thread:
992 B.addAttribute(Attribute::SanitizeThread); break;
993 case lltok::kw_sanitize_memory:
994 B.addAttribute(Attribute::SanitizeMemory); break;
995 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000996
997 // Error handling.
998 case lltok::kw_inreg:
999 case lltok::kw_signext:
1000 case lltok::kw_zeroext:
1001 HaveError |=
1002 Error(Lex.getLoc(),
1003 "invalid use of attribute on a function");
1004 break;
1005 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001006 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001007 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001008 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001009 case lltok::kw_nest:
1010 case lltok::kw_noalias:
1011 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001012 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001013 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001014 case lltok::kw_sret:
1015 HaveError |=
1016 Error(Lex.getLoc(),
1017 "invalid use of parameter-only attribute on a function");
1018 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001019 }
1020
1021 Lex.Lex();
1022 }
1023}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001024
1025//===----------------------------------------------------------------------===//
1026// GlobalValue Reference/Resolution Routines.
1027//===----------------------------------------------------------------------===//
1028
1029/// GetGlobalVal - Get a value with the specified name or ID, creating a
1030/// forward reference record if needed. This can return null if the value
1031/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001032GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001033 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001034 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001035 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001036 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001037 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001038 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001039
Chris Lattnerac161bf2009-01-02 07:01:27 +00001040 // Look this name up in the normal function symbol table.
1041 GlobalValue *Val =
1042 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001043
Chris Lattnerac161bf2009-01-02 07:01:27 +00001044 // If this is a forward reference for the value, see if we already created a
1045 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001046 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001047 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1048 I = ForwardRefVals.find(Name);
1049 if (I != ForwardRefVals.end())
1050 Val = I->second.first;
1051 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001052
Chris Lattnerac161bf2009-01-02 07:01:27 +00001053 // If we have the value in the symbol table or fwd-ref table, return it.
1054 if (Val) {
1055 if (Val->getType() == Ty) return Val;
1056 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001057 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001058 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001059 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001060
Chris Lattnerac161bf2009-01-02 07:01:27 +00001061 // Otherwise, create a new forward reference for this value and remember it.
1062 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001063 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001064 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001065 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001066 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001067 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1068 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001069 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001070
Chris Lattnerac161bf2009-01-02 07:01:27 +00001071 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1072 return FwdVal;
1073}
1074
Chris Lattner229907c2011-07-18 04:54:35 +00001075GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1076 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001077 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001078 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001079 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001080 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001081
Craig Topper2617dcc2014-04-15 06:32:26 +00001082 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001083
Chris Lattnerac161bf2009-01-02 07:01:27 +00001084 // If this is a forward reference for the value, see if we already created a
1085 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001086 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001087 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1088 I = ForwardRefValIDs.find(ID);
1089 if (I != ForwardRefValIDs.end())
1090 Val = I->second.first;
1091 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001092
Chris Lattnerac161bf2009-01-02 07:01:27 +00001093 // If we have the value in the symbol table or fwd-ref table, return it.
1094 if (Val) {
1095 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001096 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001097 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001098 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001099 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001100
Chris Lattnerac161bf2009-01-02 07:01:27 +00001101 // Otherwise, create a new forward reference for this value and remember it.
1102 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001103 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001104 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001105 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001106 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001107 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001108
Chris Lattnerac161bf2009-01-02 07:01:27 +00001109 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1110 return FwdVal;
1111}
1112
1113
1114//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001115// Comdat Reference/Resolution Routines.
1116//===----------------------------------------------------------------------===//
1117
1118Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1119 // Look this name up in the comdat symbol table.
1120 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1121 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1122 if (I != ComdatSymTab.end())
1123 return &I->second;
1124
1125 // Otherwise, create a new forward reference for this value and remember it.
1126 Comdat *C = M->getOrInsertComdat(Name);
1127 ForwardRefComdats[Name] = Loc;
1128 return C;
1129}
1130
1131
1132//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001133// Helper Routines.
1134//===----------------------------------------------------------------------===//
1135
1136/// ParseToken - If the current token has the specified kind, eat it and return
1137/// success. Otherwise, emit the specified error and return failure.
1138bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1139 if (Lex.getKind() != T)
1140 return TokError(ErrMsg);
1141 Lex.Lex();
1142 return false;
1143}
1144
Chris Lattner3822f632009-01-02 08:05:26 +00001145/// ParseStringConstant
1146/// ::= StringConstant
1147bool LLParser::ParseStringConstant(std::string &Result) {
1148 if (Lex.getKind() != lltok::StringConstant)
1149 return TokError("expected string constant");
1150 Result = Lex.getStrVal();
1151 Lex.Lex();
1152 return false;
1153}
1154
1155/// ParseUInt32
1156/// ::= uint32
1157bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001158 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1159 return TokError("expected integer");
1160 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1161 if (Val64 != unsigned(Val64))
1162 return TokError("expected 32-bit integer (too large)");
1163 Val = Val64;
1164 Lex.Lex();
1165 return false;
1166}
1167
Hal Finkelb0407ba2014-07-18 15:51:28 +00001168/// ParseUInt64
1169/// ::= uint64
1170bool LLParser::ParseUInt64(uint64_t &Val) {
1171 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1172 return TokError("expected integer");
1173 Val = Lex.getAPSIntVal().getLimitedValue();
1174 Lex.Lex();
1175 return false;
1176}
1177
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001178/// ParseTLSModel
1179/// := 'localdynamic'
1180/// := 'initialexec'
1181/// := 'localexec'
1182bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1183 switch (Lex.getKind()) {
1184 default:
1185 return TokError("expected localdynamic, initialexec or localexec");
1186 case lltok::kw_localdynamic:
1187 TLM = GlobalVariable::LocalDynamicTLSModel;
1188 break;
1189 case lltok::kw_initialexec:
1190 TLM = GlobalVariable::InitialExecTLSModel;
1191 break;
1192 case lltok::kw_localexec:
1193 TLM = GlobalVariable::LocalExecTLSModel;
1194 break;
1195 }
1196
1197 Lex.Lex();
1198 return false;
1199}
1200
1201/// ParseOptionalThreadLocal
1202/// := /*empty*/
1203/// := 'thread_local'
1204/// := 'thread_local' '(' tlsmodel ')'
1205bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1206 TLM = GlobalVariable::NotThreadLocal;
1207 if (!EatIfPresent(lltok::kw_thread_local))
1208 return false;
1209
1210 TLM = GlobalVariable::GeneralDynamicTLSModel;
1211 if (Lex.getKind() == lltok::lparen) {
1212 Lex.Lex();
1213 return ParseTLSModel(TLM) ||
1214 ParseToken(lltok::rparen, "expected ')' after thread local model");
1215 }
1216 return false;
1217}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001218
1219/// ParseOptionalAddrSpace
1220/// := /*empty*/
1221/// := 'addrspace' '(' uint32 ')'
1222bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1223 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001224 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001225 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001226 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001227 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001228 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001229}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001230
Bill Wendling34c2eb22012-12-04 23:40:58 +00001231/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1232bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1233 bool HaveError = false;
1234
1235 B.clear();
1236
1237 while (1) {
1238 lltok::Kind Token = Lex.getKind();
1239 switch (Token) {
1240 default: // End of attributes.
1241 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001242 case lltok::kw_align: {
1243 unsigned Alignment;
1244 if (ParseOptionalAlignment(Alignment))
1245 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001246 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001247 continue;
1248 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001249 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001250 case lltok::kw_dereferenceable: {
1251 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001252 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001253 return true;
1254 B.addDereferenceableAttr(Bytes);
1255 continue;
1256 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001257 case lltok::kw_dereferenceable_or_null: {
1258 uint64_t Bytes;
1259 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1260 return true;
1261 B.addDereferenceableOrNullAttr(Bytes);
1262 continue;
1263 }
Reid Klecknera534a382013-12-19 02:14:12 +00001264 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001265 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1266 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1267 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1268 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001269 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001270 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1271 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001272 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001273 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1274 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1275 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001276
Stephen Lin7577ed52013-04-20 13:16:13 +00001277 case lltok::kw_alignstack:
1278 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001279 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001280 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001281 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001282 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001283 case lltok::kw_minsize:
1284 case lltok::kw_naked:
1285 case lltok::kw_nobuiltin:
1286 case lltok::kw_noduplicate:
1287 case lltok::kw_noimplicitfloat:
1288 case lltok::kw_noinline:
1289 case lltok::kw_nonlazybind:
1290 case lltok::kw_noredzone:
1291 case lltok::kw_noreturn:
1292 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001293 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001294 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001295 case lltok::kw_returns_twice:
1296 case lltok::kw_sanitize_address:
1297 case lltok::kw_sanitize_memory:
1298 case lltok::kw_sanitize_thread:
1299 case lltok::kw_ssp:
1300 case lltok::kw_sspreq:
1301 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001302 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001303 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001304 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1305 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001306 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001307
Bill Wendling34c2eb22012-12-04 23:40:58 +00001308 Lex.Lex();
1309 }
1310}
1311
1312/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1313bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1314 bool HaveError = false;
1315
1316 B.clear();
1317
1318 while (1) {
1319 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001320 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001321 default: // End of attributes.
1322 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001323 case lltok::kw_dereferenceable: {
1324 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001325 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001326 return true;
1327 B.addDereferenceableAttr(Bytes);
1328 continue;
1329 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001330 case lltok::kw_dereferenceable_or_null: {
1331 uint64_t Bytes;
1332 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1333 return true;
1334 B.addDereferenceableOrNullAttr(Bytes);
1335 continue;
1336 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001337 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1338 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001339 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001340 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1341 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001342
Bill Wendling34c2eb22012-12-04 23:40:58 +00001343 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001344 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001345 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001346 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001347 case lltok::kw_nest:
1348 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001349 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001350 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001351 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001352 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001353
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001354 case lltok::kw_alignstack:
1355 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001356 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001357 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001358 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001359 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001360 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001361 case lltok::kw_minsize:
1362 case lltok::kw_naked:
1363 case lltok::kw_nobuiltin:
1364 case lltok::kw_noduplicate:
1365 case lltok::kw_noimplicitfloat:
1366 case lltok::kw_noinline:
1367 case lltok::kw_nonlazybind:
1368 case lltok::kw_noredzone:
1369 case lltok::kw_noreturn:
1370 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001371 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001372 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001373 case lltok::kw_returns_twice:
1374 case lltok::kw_sanitize_address:
1375 case lltok::kw_sanitize_memory:
1376 case lltok::kw_sanitize_thread:
1377 case lltok::kw_ssp:
1378 case lltok::kw_sspreq:
1379 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001380 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001381 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001382 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001383 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001384
1385 case lltok::kw_readnone:
1386 case lltok::kw_readonly:
1387 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001388 }
1389
Chris Lattnerac161bf2009-01-02 07:01:27 +00001390 Lex.Lex();
1391 }
1392}
1393
1394/// ParseOptionalLinkage
1395/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001396/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001397/// ::= 'internal'
1398/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001399/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001400/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001401/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001402/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001403/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001404/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001405/// ::= 'extern_weak'
1406/// ::= 'external'
1407bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1408 HasLinkage = false;
1409 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001410 default: Res=GlobalValue::ExternalLinkage; return false;
1411 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001412 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1413 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1414 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1415 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1416 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001417 case lltok::kw_available_externally:
1418 Res = GlobalValue::AvailableExternallyLinkage;
1419 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001420 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001421 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001422 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1423 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001424 }
1425 Lex.Lex();
1426 HasLinkage = true;
1427 return false;
1428}
1429
1430/// ParseOptionalVisibility
1431/// ::= /*empty*/
1432/// ::= 'default'
1433/// ::= 'hidden'
1434/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001435///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001436bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1437 switch (Lex.getKind()) {
1438 default: Res = GlobalValue::DefaultVisibility; return false;
1439 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1440 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1441 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1442 }
1443 Lex.Lex();
1444 return false;
1445}
1446
Nico Rieck7157bb72014-01-14 15:22:47 +00001447/// ParseOptionalDLLStorageClass
1448/// ::= /*empty*/
1449/// ::= 'dllimport'
1450/// ::= 'dllexport'
1451///
1452bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1453 switch (Lex.getKind()) {
1454 default: Res = GlobalValue::DefaultStorageClass; return false;
1455 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1456 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1457 }
1458 Lex.Lex();
1459 return false;
1460}
1461
Chris Lattnerac161bf2009-01-02 07:01:27 +00001462/// ParseOptionalCallingConv
1463/// ::= /*empty*/
1464/// ::= 'ccc'
1465/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001466/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001467/// ::= 'coldcc'
1468/// ::= 'x86_stdcallcc'
1469/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001470/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001471/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001472/// ::= 'arm_apcscc'
1473/// ::= 'arm_aapcscc'
1474/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001475/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001476/// ::= 'ptx_kernel'
1477/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001478/// ::= 'spir_func'
1479/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001480/// ::= 'x86_64_sysvcc'
1481/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001482/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001483/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001484/// ::= 'preserve_mostcc'
1485/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001486/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001487/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001488///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001489bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001490 switch (Lex.getKind()) {
1491 default: CC = CallingConv::C; return false;
1492 case lltok::kw_ccc: CC = CallingConv::C; break;
1493 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1494 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1495 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1496 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001497 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001498 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001499 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1500 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1501 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001502 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001503 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1504 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001505 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1506 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001507 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001508 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1509 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001510 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001511 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001512 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1513 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001514 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001515 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001516 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001517 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001518 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001519 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001520
Chris Lattnerac161bf2009-01-02 07:01:27 +00001521 Lex.Lex();
1522 return false;
1523}
1524
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001525/// ParseMetadataAttachment
1526/// ::= !dbg !42
1527bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1528 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1529
1530 std::string Name = Lex.getStrVal();
1531 Kind = M->getMDKindID(Name);
1532 Lex.Lex();
1533
1534 return ParseMDNode(MD);
1535}
1536
Chris Lattner5c427632009-12-30 05:31:19 +00001537/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001538/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001539bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001540 do {
1541 if (Lex.getKind() != lltok::MetadataVar)
1542 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001543
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001544 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001545 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001546 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001547 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001548
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001549 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001550 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001551 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001552
Chris Lattner596760d2009-12-29 21:25:40 +00001553 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001554 } while (EatIfPresent(lltok::comma));
1555 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001556}
1557
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001558/// ParseOptionalFunctionMetadata
1559/// ::= (!dbg !57)*
1560bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1561 while (Lex.getKind() == lltok::MetadataVar) {
1562 unsigned MDK;
1563 MDNode *N;
1564 if (ParseMetadataAttachment(MDK, N))
1565 return true;
1566
1567 F.setMetadata(MDK, N);
1568 }
1569 return false;
1570}
1571
Chris Lattnerac161bf2009-01-02 07:01:27 +00001572/// ParseOptionalAlignment
1573/// ::= /* empty */
1574/// ::= 'align' 4
1575bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1576 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001577 if (!EatIfPresent(lltok::kw_align))
1578 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001579 LocTy AlignLoc = Lex.getLoc();
1580 if (ParseUInt32(Alignment)) return true;
1581 if (!isPowerOf2_32(Alignment))
1582 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001583 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001584 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001585 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001586}
1587
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001588/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001589/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001590/// ::= AttrKind '(' 4 ')'
1591///
1592/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1593bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1594 uint64_t &Bytes) {
1595 assert((AttrKind == lltok::kw_dereferenceable ||
1596 AttrKind == lltok::kw_dereferenceable_or_null) &&
1597 "contract!");
1598
Hal Finkelb0407ba2014-07-18 15:51:28 +00001599 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001600 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001601 return false;
1602 LocTy ParenLoc = Lex.getLoc();
1603 if (!EatIfPresent(lltok::lparen))
1604 return Error(ParenLoc, "expected '('");
1605 LocTy DerefLoc = Lex.getLoc();
1606 if (ParseUInt64(Bytes)) return true;
1607 ParenLoc = Lex.getLoc();
1608 if (!EatIfPresent(lltok::rparen))
1609 return Error(ParenLoc, "expected ')'");
1610 if (!Bytes)
1611 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1612 return false;
1613}
1614
Chris Lattnerb2f39502009-12-30 05:44:30 +00001615/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001616/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001617/// ::= ',' align 4
1618///
1619/// This returns with AteExtraComma set to true if it ate an excess comma at the
1620/// end.
1621bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1622 bool &AteExtraComma) {
1623 AteExtraComma = false;
1624 while (EatIfPresent(lltok::comma)) {
1625 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001626 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001627 AteExtraComma = true;
1628 return false;
1629 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001630
Chris Lattner95b0ff42010-04-23 00:50:50 +00001631 if (Lex.getKind() != lltok::kw_align)
1632 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001633
Chris Lattner95b0ff42010-04-23 00:50:50 +00001634 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001635 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001636
Devang Patelea8a4b92009-09-17 23:04:48 +00001637 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001638}
1639
Eli Friedmanfee02c62011-07-25 23:16:38 +00001640/// ParseScopeAndOrdering
1641/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1642/// else: ::=
1643///
1644/// This sets Scope and Ordering to the parsed values.
1645bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1646 AtomicOrdering &Ordering) {
1647 if (!isAtomic)
1648 return false;
1649
1650 Scope = CrossThread;
1651 if (EatIfPresent(lltok::kw_singlethread))
1652 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001653
1654 return ParseOrdering(Ordering);
1655}
1656
1657/// ParseOrdering
1658/// ::= AtomicOrdering
1659///
1660/// This sets Ordering to the parsed value.
1661bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001662 switch (Lex.getKind()) {
1663 default: return TokError("Expected ordering on atomic instruction");
1664 case lltok::kw_unordered: Ordering = Unordered; break;
1665 case lltok::kw_monotonic: Ordering = Monotonic; break;
1666 case lltok::kw_acquire: Ordering = Acquire; break;
1667 case lltok::kw_release: Ordering = Release; break;
1668 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1669 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1670 }
1671 Lex.Lex();
1672 return false;
1673}
1674
Charles Davisbe5557e2010-02-12 00:31:15 +00001675/// ParseOptionalStackAlignment
1676/// ::= /* empty */
1677/// ::= 'alignstack' '(' 4 ')'
1678bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1679 Alignment = 0;
1680 if (!EatIfPresent(lltok::kw_alignstack))
1681 return false;
1682 LocTy ParenLoc = Lex.getLoc();
1683 if (!EatIfPresent(lltok::lparen))
1684 return Error(ParenLoc, "expected '('");
1685 LocTy AlignLoc = Lex.getLoc();
1686 if (ParseUInt32(Alignment)) return true;
1687 ParenLoc = Lex.getLoc();
1688 if (!EatIfPresent(lltok::rparen))
1689 return Error(ParenLoc, "expected ')'");
1690 if (!isPowerOf2_32(Alignment))
1691 return Error(AlignLoc, "stack alignment is not a power of two");
1692 return false;
1693}
Devang Patelea8a4b92009-09-17 23:04:48 +00001694
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001695/// ParseIndexList - This parses the index list for an insert/extractvalue
1696/// instruction. This sets AteExtraComma in the case where we eat an extra
1697/// comma at the end of the line and find that it is followed by metadata.
1698/// Clients that don't allow metadata can call the version of this function that
1699/// only takes one argument.
1700///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001701/// ParseIndexList
1702/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001703///
1704bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1705 bool &AteExtraComma) {
1706 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001707
Chris Lattnerac161bf2009-01-02 07:01:27 +00001708 if (Lex.getKind() != lltok::comma)
1709 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001710
Chris Lattner3822f632009-01-02 08:05:26 +00001711 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001712 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001713 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001714 AteExtraComma = true;
1715 return false;
1716 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001717 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001718 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001719 Indices.push_back(Idx);
1720 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001721
Chris Lattnerac161bf2009-01-02 07:01:27 +00001722 return false;
1723}
1724
1725//===----------------------------------------------------------------------===//
1726// Type Parsing.
1727//===----------------------------------------------------------------------===//
1728
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001729/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001730bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001731 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001732 switch (Lex.getKind()) {
1733 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001734 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001735 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001736 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001737 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001738 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001739 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001740 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001741 // Type ::= StructType
1742 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001743 return true;
1744 break;
1745 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001746 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001747 Lex.Lex(); // eat the lsquare.
1748 if (ParseArrayVectorType(Result, false))
1749 return true;
1750 break;
1751 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001752 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001753 Lex.Lex();
1754 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001755 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001756 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001757 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001758 } else if (ParseArrayVectorType(Result, true))
1759 return true;
1760 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001761 case lltok::LocalVar: {
1762 // Type ::= %foo
1763 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001764
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001765 // If the type hasn't been defined yet, create a forward definition and
1766 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001767 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001768 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001769 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001770 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001771 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001772 Lex.Lex();
1773 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001774 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001775
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001776 case lltok::LocalVarID: {
1777 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001778 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001779
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001780 // If the type hasn't been defined yet, create a forward definition and
1781 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001782 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001783 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001784 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001785 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001786 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001787 Lex.Lex();
1788 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001789 }
1790 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001791
1792 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001793 while (1) {
1794 switch (Lex.getKind()) {
1795 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001796 default:
1797 if (!AllowVoid && Result->isVoidTy())
1798 return Error(TypeLoc, "void type only allowed for function results");
1799 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001800
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001801 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001802 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001803 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001804 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001805 if (Result->isVoidTy())
1806 return TokError("pointers to void are invalid - use i8* instead");
1807 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001808 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001809 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001810 Lex.Lex();
1811 break;
1812
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001813 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001814 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001815 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001816 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001817 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001818 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001819 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001820 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001821 unsigned AddrSpace;
1822 if (ParseOptionalAddrSpace(AddrSpace) ||
1823 ParseToken(lltok::star, "expected '*' in address space"))
1824 return true;
1825
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001826 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001827 break;
1828 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001829
Chris Lattnerac161bf2009-01-02 07:01:27 +00001830 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1831 case lltok::lparen:
1832 if (ParseFunctionType(Result))
1833 return true;
1834 break;
1835 }
1836 }
1837}
1838
1839/// ParseParameterList
1840/// ::= '(' ')'
1841/// ::= '(' Arg (',' Arg)* ')'
1842/// Arg
1843/// ::= Type OptionalAttributes Value OptionalAttributes
1844bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001845 PerFunctionState &PFS, bool IsMustTailCall,
1846 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001847 if (ParseToken(lltok::lparen, "expected '(' in call"))
1848 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001849
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001850 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001851 while (Lex.getKind() != lltok::rparen) {
1852 // If this isn't the first argument, we need a comma.
1853 if (!ArgList.empty() &&
1854 ParseToken(lltok::comma, "expected ',' in argument list"))
1855 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001856
Reid Kleckner83498642014-08-26 00:33:28 +00001857 // Parse an ellipsis if this is a musttail call in a variadic function.
1858 if (Lex.getKind() == lltok::dotdotdot) {
1859 const char *Msg = "unexpected ellipsis in argument list for ";
1860 if (!IsMustTailCall)
1861 return TokError(Twine(Msg) + "non-musttail call");
1862 if (!InVarArgsFunc)
1863 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1864 Lex.Lex(); // Lex the '...', it is purely for readability.
1865 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1866 }
1867
Chris Lattnerac161bf2009-01-02 07:01:27 +00001868 // Parse the argument.
1869 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001870 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001871 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001872 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001873 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001874 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001875
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001876 if (ArgTy->isMetadataTy()) {
1877 if (ParseMetadataAsValue(V, PFS))
1878 return true;
1879 } else {
1880 // Otherwise, handle normal operands.
1881 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1882 return true;
1883 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001884 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1885 AttrIndex++,
1886 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001887 }
1888
Reid Kleckner83498642014-08-26 00:33:28 +00001889 if (IsMustTailCall && InVarArgsFunc)
1890 return TokError("expected '...' at end of argument list for musttail call "
1891 "in varargs function");
1892
Chris Lattnerac161bf2009-01-02 07:01:27 +00001893 Lex.Lex(); // Lex the ')'.
1894 return false;
1895}
1896
1897
1898
Chris Lattner2ed06b42009-01-05 18:34:07 +00001899/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001900/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001901/// ::= '(' ArgTypeListI ')'
1902/// ArgTypeListI
1903/// ::= /*empty*/
1904/// ::= '...'
1905/// ::= ArgTypeList ',' '...'
1906/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001907///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001908bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1909 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001910 isVarArg = false;
1911 assert(Lex.getKind() == lltok::lparen);
1912 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001913
Chris Lattnerac161bf2009-01-02 07:01:27 +00001914 if (Lex.getKind() == lltok::rparen) {
1915 // empty
1916 } else if (Lex.getKind() == lltok::dotdotdot) {
1917 isVarArg = true;
1918 Lex.Lex();
1919 } else {
1920 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001921 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001922 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001923 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001924
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001925 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001926 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001927
Chris Lattnerfdd87902009-10-05 05:54:46 +00001928 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001929 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001930
Chris Lattnerdef19492011-06-17 06:36:20 +00001931 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001932 Name = Lex.getStrVal();
1933 Lex.Lex();
1934 }
Chris Lattner3822f632009-01-02 08:05:26 +00001935
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001936 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001937 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001938
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001939 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001940 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
1941 AttrIndex++, Attrs),
1942 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001943
Chris Lattner3822f632009-01-02 08:05:26 +00001944 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001945 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001946 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001947 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001948 break;
1949 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001950
Chris Lattnerac161bf2009-01-02 07:01:27 +00001951 // Otherwise must be an argument type.
1952 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001953 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001954
Chris Lattnerfdd87902009-10-05 05:54:46 +00001955 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001956 return Error(TypeLoc, "argument can not have void type");
1957
Chris Lattnerdef19492011-06-17 06:36:20 +00001958 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001959 Name = Lex.getStrVal();
1960 Lex.Lex();
1961 } else {
1962 Name = "";
1963 }
Chris Lattner3822f632009-01-02 08:05:26 +00001964
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001965 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001966 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001967
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001968 ArgList.emplace_back(
1969 TypeLoc, ArgTy,
1970 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
1971 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001972 }
1973 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001974
Chris Lattner3822f632009-01-02 08:05:26 +00001975 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001976}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001977
Chris Lattnerac161bf2009-01-02 07:01:27 +00001978/// ParseFunctionType
1979/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001980bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001981 assert(Lex.getKind() == lltok::lparen);
1982
Chris Lattnerce473c72009-01-05 08:04:33 +00001983 if (!FunctionType::isValidReturnType(Result))
1984 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001985
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001986 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001987 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001988 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001989 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001990
Chris Lattnerac161bf2009-01-02 07:01:27 +00001991 // Reject names on the arguments lists.
1992 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1993 if (!ArgList[i].Name.empty())
1994 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001995 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001996 return Error(ArgList[i].Loc,
1997 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001998 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001999
Jay Foadb804a2b2011-07-12 14:06:48 +00002000 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002001 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002002 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002003
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002004 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002005 return false;
2006}
2007
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002008/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2009/// other structs.
2010bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2011 SmallVector<Type*, 8> Elts;
2012 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002013
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002014 Result = StructType::get(Context, Elts, Packed);
2015 return false;
2016}
2017
2018/// ParseStructDefinition - Parse a struct in a 'type' definition.
2019bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2020 std::pair<Type*, LocTy> &Entry,
2021 Type *&ResultTy) {
2022 // If the type was already defined, diagnose the redefinition.
2023 if (Entry.first && !Entry.second.isValid())
2024 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002025
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002026 // If we have opaque, just return without filling in the definition for the
2027 // struct. This counts as a definition as far as the .ll file goes.
2028 if (EatIfPresent(lltok::kw_opaque)) {
2029 // This type is being defined, so clear the location to indicate this.
2030 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002031
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002032 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002033 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002034 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002035 ResultTy = Entry.first;
2036 return false;
2037 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002038
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002039 // If the type starts with '<', then it is either a packed struct or a vector.
2040 bool isPacked = EatIfPresent(lltok::less);
2041
2042 // If we don't have a struct, then we have a random type alias, which we
2043 // accept for compatibility with old files. These types are not allowed to be
2044 // forward referenced and not allowed to be recursive.
2045 if (Lex.getKind() != lltok::lbrace) {
2046 if (Entry.first)
2047 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002048
Craig Topper2617dcc2014-04-15 06:32:26 +00002049 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002050 if (isPacked)
2051 return ParseArrayVectorType(ResultTy, true);
2052 return ParseType(ResultTy);
2053 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002054
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002055 // This type is being defined, so clear the location to indicate this.
2056 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002057
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002058 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002059 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002060 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002061
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002062 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002063
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002064 SmallVector<Type*, 8> Body;
2065 if (ParseStructBody(Body) ||
2066 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2067 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002068
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002069 STy->setBody(Body, isPacked);
2070 ResultTy = STy;
2071 return false;
2072}
2073
2074
Chris Lattnerac161bf2009-01-02 07:01:27 +00002075/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002076/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002077/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002078/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002079/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002080/// ::= '<' '{' Type (',' Type)* '}' '>'
2081bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002082 assert(Lex.getKind() == lltok::lbrace);
2083 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002084
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002085 // Handle the empty struct.
2086 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002087 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002088
Chris Lattnerf880ca22009-03-09 04:49:14 +00002089 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002090 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002091 if (ParseType(Ty)) return true;
2092 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002093
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002094 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002095 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002096
Chris Lattner3822f632009-01-02 08:05:26 +00002097 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002098 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002099 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002100
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002101 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002102 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002103
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002104 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002105 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002106
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002107 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002108}
2109
2110/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2111/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002112/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002113/// ::= '[' APSINTVAL 'x' Types ']'
2114/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002115bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002116 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2117 Lex.getAPSIntVal().getBitWidth() > 64)
2118 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002119
Chris Lattnerac161bf2009-01-02 07:01:27 +00002120 LocTy SizeLoc = Lex.getLoc();
2121 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002122 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002123
Chris Lattner3822f632009-01-02 08:05:26 +00002124 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2125 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002126
2127 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002128 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002129 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002130
Chris Lattner3822f632009-01-02 08:05:26 +00002131 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2132 "expected end of sequential type"))
2133 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002134
Chris Lattnerac161bf2009-01-02 07:01:27 +00002135 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002136 if (Size == 0)
2137 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002138 if ((unsigned)Size != Size)
2139 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002140 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002141 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002142 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002143 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002144 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002145 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002146 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002147 }
2148 return false;
2149}
2150
2151//===----------------------------------------------------------------------===//
2152// Function Semantic Analysis.
2153//===----------------------------------------------------------------------===//
2154
Chris Lattner3432c622009-10-28 03:39:23 +00002155LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2156 int functionNumber)
2157 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002158
2159 // Insert unnamed arguments into the NumberedVals list.
2160 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2161 AI != E; ++AI)
2162 if (!AI->hasName())
2163 NumberedVals.push_back(AI);
2164}
2165
2166LLParser::PerFunctionState::~PerFunctionState() {
2167 // If there were any forward referenced non-basicblock values, delete them.
2168 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2169 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2170 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002171 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002172 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002173 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002174 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002175 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002176
Chris Lattnerac161bf2009-01-02 07:01:27 +00002177 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2178 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2179 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002180 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002181 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002182 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002183 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002184 }
2185}
2186
Chris Lattner3432c622009-10-28 03:39:23 +00002187bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002188 if (!ForwardRefVals.empty())
2189 return P.Error(ForwardRefVals.begin()->second.second,
2190 "use of undefined value '%" + ForwardRefVals.begin()->first +
2191 "'");
2192 if (!ForwardRefValIDs.empty())
2193 return P.Error(ForwardRefValIDs.begin()->second.second,
2194 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002195 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002196 return false;
2197}
2198
2199
2200/// GetVal - Get a value with the specified name or ID, creating a
2201/// forward reference record if needed. This can return null if the value
2202/// exists but does not have the right type.
2203Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002204 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002205 // Look this name up in the normal function symbol table.
2206 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002207
Chris Lattnerac161bf2009-01-02 07:01:27 +00002208 // If this is a forward reference for the value, see if we already created a
2209 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002210 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002211 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2212 I = ForwardRefVals.find(Name);
2213 if (I != ForwardRefVals.end())
2214 Val = I->second.first;
2215 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002216
Chris Lattnerac161bf2009-01-02 07:01:27 +00002217 // If we have the value in the symbol table or fwd-ref table, return it.
2218 if (Val) {
2219 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002220 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002221 P.Error(Loc, "'%" + Name + "' is not a basic block");
2222 else
2223 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002224 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002225 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002226 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002227
Chris Lattnerac161bf2009-01-02 07:01:27 +00002228 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002229 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002230 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002231 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002232 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002233
Chris Lattnerac161bf2009-01-02 07:01:27 +00002234 // Otherwise, create a new forward reference for this value and remember it.
2235 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002236 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002237 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002238 else
2239 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002240
Chris Lattnerac161bf2009-01-02 07:01:27 +00002241 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2242 return FwdVal;
2243}
2244
Chris Lattner229907c2011-07-18 04:54:35 +00002245Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002246 LocTy Loc) {
2247 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002248 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002249
Chris Lattnerac161bf2009-01-02 07:01:27 +00002250 // If this is a forward reference for the value, see if we already created a
2251 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002252 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002253 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2254 I = ForwardRefValIDs.find(ID);
2255 if (I != ForwardRefValIDs.end())
2256 Val = I->second.first;
2257 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002258
Chris Lattnerac161bf2009-01-02 07:01:27 +00002259 // If we have the value in the symbol table or fwd-ref table, return it.
2260 if (Val) {
2261 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002262 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002263 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002264 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002265 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002266 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002267 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002268 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002269
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002270 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002271 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002272 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002273 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002274
Chris Lattnerac161bf2009-01-02 07:01:27 +00002275 // Otherwise, create a new forward reference for this value and remember it.
2276 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002277 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002278 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002279 else
2280 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002281
Chris Lattnerac161bf2009-01-02 07:01:27 +00002282 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2283 return FwdVal;
2284}
2285
2286/// SetInstName - After an instruction is parsed and inserted into its
2287/// basic block, this installs its name.
2288bool LLParser::PerFunctionState::SetInstName(int NameID,
2289 const std::string &NameStr,
2290 LocTy NameLoc, Instruction *Inst) {
2291 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002292 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002293 if (NameID != -1 || !NameStr.empty())
2294 return P.Error(NameLoc, "instructions returning void cannot have a name");
2295 return false;
2296 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002297
Chris Lattnerac161bf2009-01-02 07:01:27 +00002298 // If this was a numbered instruction, verify that the instruction is the
2299 // expected value and resolve any forward references.
2300 if (NameStr.empty()) {
2301 // If neither a name nor an ID was specified, just use the next ID.
2302 if (NameID == -1)
2303 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002304
Chris Lattnerac161bf2009-01-02 07:01:27 +00002305 if (unsigned(NameID) != NumberedVals.size())
2306 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002307 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002308
Chris Lattnerac161bf2009-01-02 07:01:27 +00002309 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2310 ForwardRefValIDs.find(NameID);
2311 if (FI != ForwardRefValIDs.end()) {
2312 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002313 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002314 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002315 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002316 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002317 ForwardRefValIDs.erase(FI);
2318 }
2319
2320 NumberedVals.push_back(Inst);
2321 return false;
2322 }
2323
2324 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2325 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2326 FI = ForwardRefVals.find(NameStr);
2327 if (FI != ForwardRefVals.end()) {
2328 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002329 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002330 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002331 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002332 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002333 ForwardRefVals.erase(FI);
2334 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002335
Chris Lattnerac161bf2009-01-02 07:01:27 +00002336 // Set the name on the instruction.
2337 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002338
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002339 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002340 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002341 NameStr + "'");
2342 return false;
2343}
2344
2345/// GetBB - Get a basic block with the specified name or ID, creating a
2346/// forward reference record if needed.
2347BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2348 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002349 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2350 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002351}
2352
2353BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002354 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2355 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002356}
2357
2358/// DefineBB - Define the specified basic block, which is either named or
2359/// unnamed. If there is an error, this returns null otherwise it returns
2360/// the block being defined.
2361BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2362 LocTy Loc) {
2363 BasicBlock *BB;
2364 if (Name.empty())
2365 BB = GetBB(NumberedVals.size(), Loc);
2366 else
2367 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002368 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002369
Chris Lattnerac161bf2009-01-02 07:01:27 +00002370 // Move the block to the end of the function. Forward ref'd blocks are
2371 // inserted wherever they happen to be referenced.
2372 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002373
Chris Lattnerac161bf2009-01-02 07:01:27 +00002374 // Remove the block from forward ref sets.
2375 if (Name.empty()) {
2376 ForwardRefValIDs.erase(NumberedVals.size());
2377 NumberedVals.push_back(BB);
2378 } else {
2379 // BB forward references are already in the function symbol table.
2380 ForwardRefVals.erase(Name);
2381 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002382
Chris Lattnerac161bf2009-01-02 07:01:27 +00002383 return BB;
2384}
2385
2386//===----------------------------------------------------------------------===//
2387// Constants.
2388//===----------------------------------------------------------------------===//
2389
2390/// ParseValID - Parse an abstract value that doesn't necessarily have a
2391/// type implied. For example, if we parse "4" we don't know what integer type
2392/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002393/// sanity. PFS is used to convert function-local operands of metadata (since
2394/// metadata operands are not just parsed here but also converted to values).
2395/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002396bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002397 ID.Loc = Lex.getLoc();
2398 switch (Lex.getKind()) {
2399 default: return TokError("expected value token");
2400 case lltok::GlobalID: // @42
2401 ID.UIntVal = Lex.getUIntVal();
2402 ID.Kind = ValID::t_GlobalID;
2403 break;
2404 case lltok::GlobalVar: // @foo
2405 ID.StrVal = Lex.getStrVal();
2406 ID.Kind = ValID::t_GlobalName;
2407 break;
2408 case lltok::LocalVarID: // %42
2409 ID.UIntVal = Lex.getUIntVal();
2410 ID.Kind = ValID::t_LocalID;
2411 break;
2412 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002413 ID.StrVal = Lex.getStrVal();
2414 ID.Kind = ValID::t_LocalName;
2415 break;
2416 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002417 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002418 ID.Kind = ValID::t_APSInt;
2419 break;
2420 case lltok::APFloat:
2421 ID.APFloatVal = Lex.getAPFloatVal();
2422 ID.Kind = ValID::t_APFloat;
2423 break;
2424 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002425 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002426 ID.Kind = ValID::t_Constant;
2427 break;
2428 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002429 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002430 ID.Kind = ValID::t_Constant;
2431 break;
2432 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2433 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2434 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002435
Chris Lattnerac161bf2009-01-02 07:01:27 +00002436 case lltok::lbrace: {
2437 // ValID ::= '{' ConstVector '}'
2438 Lex.Lex();
2439 SmallVector<Constant*, 16> Elts;
2440 if (ParseGlobalValueVector(Elts) ||
2441 ParseToken(lltok::rbrace, "expected end of struct constant"))
2442 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002443
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002444 ID.ConstantStructElts = new Constant*[Elts.size()];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002445 ID.UIntVal = Elts.size();
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002446 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002447 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002448 return false;
2449 }
2450 case lltok::less: {
2451 // ValID ::= '<' ConstVector '>' --> Vector.
2452 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2453 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002454 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002455
Chris Lattnerac161bf2009-01-02 07:01:27 +00002456 SmallVector<Constant*, 16> Elts;
2457 LocTy FirstEltLoc = Lex.getLoc();
2458 if (ParseGlobalValueVector(Elts) ||
2459 (isPackedStruct &&
2460 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2461 ParseToken(lltok::greater, "expected end of constant"))
2462 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002463
Chris Lattnerac161bf2009-01-02 07:01:27 +00002464 if (isPackedStruct) {
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002465 ID.ConstantStructElts = new Constant*[Elts.size()];
2466 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002467 ID.UIntVal = Elts.size();
2468 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002469 return false;
2470 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002471
Chris Lattnerac161bf2009-01-02 07:01:27 +00002472 if (Elts.empty())
2473 return Error(ID.Loc, "constant vector must not be empty");
2474
Duncan Sands9dff9be2010-02-15 16:12:20 +00002475 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002476 !Elts[0]->getType()->isFloatingPointTy() &&
2477 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002478 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002479 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002480
Chris Lattnerac161bf2009-01-02 07:01:27 +00002481 // Verify that all the vector elements have the same type.
2482 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2483 if (Elts[i]->getType() != Elts[0]->getType())
2484 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002485 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002486 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002487
Chris Lattner69229312011-02-15 00:14:00 +00002488 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002489 ID.Kind = ValID::t_Constant;
2490 return false;
2491 }
2492 case lltok::lsquare: { // Array Constant
2493 Lex.Lex();
2494 SmallVector<Constant*, 16> Elts;
2495 LocTy FirstEltLoc = Lex.getLoc();
2496 if (ParseGlobalValueVector(Elts) ||
2497 ParseToken(lltok::rsquare, "expected end of array constant"))
2498 return true;
2499
2500 // Handle empty element.
2501 if (Elts.empty()) {
2502 // Use undef instead of an array because it's inconvenient to determine
2503 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002504 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002505 return false;
2506 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002507
Chris Lattnerac161bf2009-01-02 07:01:27 +00002508 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002509 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002510 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002511
Owen Anderson4056ca92009-07-29 22:17:13 +00002512 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002513
Chris Lattnerac161bf2009-01-02 07:01:27 +00002514 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002515 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002516 if (Elts[i]->getType() != Elts[0]->getType())
2517 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002518 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002519 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002520 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002521
Jay Foad83be3612011-06-22 09:24:39 +00002522 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002523 ID.Kind = ValID::t_Constant;
2524 return false;
2525 }
2526 case lltok::kw_c: // c "foo"
2527 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002528 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2529 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002530 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2531 ID.Kind = ValID::t_Constant;
2532 return false;
2533
2534 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002535 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2536 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002537 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002538 Lex.Lex();
2539 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002540 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002541 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002542 ParseStringConstant(ID.StrVal) ||
2543 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002544 ParseToken(lltok::StringConstant, "expected constraint string"))
2545 return true;
2546 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002547 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002548 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002549 ID.Kind = ValID::t_InlineAsm;
2550 return false;
2551 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002552
Chris Lattner3432c622009-10-28 03:39:23 +00002553 case lltok::kw_blockaddress: {
2554 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2555 Lex.Lex();
2556
2557 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002558
Chris Lattner3432c622009-10-28 03:39:23 +00002559 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2560 ParseValID(Fn) ||
2561 ParseToken(lltok::comma, "expected comma in block address expression")||
2562 ParseValID(Label) ||
2563 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2564 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002565
Chris Lattner3432c622009-10-28 03:39:23 +00002566 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2567 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002568 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002569 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002570
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002571 // Try to find the function (but skip it if it's forward-referenced).
2572 GlobalValue *GV = nullptr;
2573 if (Fn.Kind == ValID::t_GlobalID) {
2574 if (Fn.UIntVal < NumberedVals.size())
2575 GV = NumberedVals[Fn.UIntVal];
2576 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2577 GV = M->getNamedValue(Fn.StrVal);
2578 }
2579 Function *F = nullptr;
2580 if (GV) {
2581 // Confirm that it's actually a function with a definition.
2582 if (!isa<Function>(GV))
2583 return Error(Fn.Loc, "expected function name in blockaddress");
2584 F = cast<Function>(GV);
2585 if (F->isDeclaration())
2586 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2587 }
2588
2589 if (!F) {
2590 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002591 GlobalValue *&FwdRef =
2592 ForwardRefBlockAddresses.insert(std::make_pair(
2593 std::move(Fn),
2594 std::map<ValID, GlobalValue *>()))
2595 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2596 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002597 if (!FwdRef)
2598 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2599 GlobalValue::InternalLinkage, nullptr, "");
2600 ID.ConstantVal = FwdRef;
2601 ID.Kind = ValID::t_Constant;
2602 return false;
2603 }
2604
2605 // We found the function; now find the basic block. Don't use PFS, since we
2606 // might be inside a constant expression.
2607 BasicBlock *BB;
2608 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2609 if (Label.Kind == ValID::t_LocalID)
2610 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2611 else
2612 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2613 if (!BB)
2614 return Error(Label.Loc, "referenced value is not a basic block");
2615 } else {
2616 if (Label.Kind == ValID::t_LocalID)
2617 return Error(Label.Loc, "cannot take address of numeric label after "
2618 "the function is defined");
2619 BB = dyn_cast_or_null<BasicBlock>(
2620 F->getValueSymbolTable().lookup(Label.StrVal));
2621 if (!BB)
2622 return Error(Label.Loc, "referenced value is not a basic block");
2623 }
2624
2625 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002626 ID.Kind = ValID::t_Constant;
2627 return false;
2628 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002629
Chris Lattnerac161bf2009-01-02 07:01:27 +00002630 case lltok::kw_trunc:
2631 case lltok::kw_zext:
2632 case lltok::kw_sext:
2633 case lltok::kw_fptrunc:
2634 case lltok::kw_fpext:
2635 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002636 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002637 case lltok::kw_uitofp:
2638 case lltok::kw_sitofp:
2639 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002640 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002641 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002642 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002643 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002644 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002645 Constant *SrcVal;
2646 Lex.Lex();
2647 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2648 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002649 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002650 ParseType(DestTy) ||
2651 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2652 return true;
2653 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2654 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002655 getTypeString(SrcVal->getType()) + "' to '" +
2656 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002657 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002658 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002659 ID.Kind = ValID::t_Constant;
2660 return false;
2661 }
2662 case lltok::kw_extractvalue: {
2663 Lex.Lex();
2664 Constant *Val;
2665 SmallVector<unsigned, 4> Indices;
2666 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2667 ParseGlobalTypeAndValue(Val) ||
2668 ParseIndexList(Indices) ||
2669 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2670 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002671
Chris Lattner392be582010-02-12 20:49:41 +00002672 if (!Val->getType()->isAggregateType())
2673 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002674 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002675 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002676 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002677 ID.Kind = ValID::t_Constant;
2678 return false;
2679 }
2680 case lltok::kw_insertvalue: {
2681 Lex.Lex();
2682 Constant *Val0, *Val1;
2683 SmallVector<unsigned, 4> Indices;
2684 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2685 ParseGlobalTypeAndValue(Val0) ||
2686 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2687 ParseGlobalTypeAndValue(Val1) ||
2688 ParseIndexList(Indices) ||
2689 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2690 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002691 if (!Val0->getType()->isAggregateType())
2692 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002693 Type *IndexedType =
2694 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2695 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002696 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002697 if (IndexedType != Val1->getType())
2698 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2699 getTypeString(Val1->getType()) +
2700 "' instead of '" + getTypeString(IndexedType) +
2701 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002702 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002703 ID.Kind = ValID::t_Constant;
2704 return false;
2705 }
2706 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002707 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002708 unsigned PredVal, Opc = Lex.getUIntVal();
2709 Constant *Val0, *Val1;
2710 Lex.Lex();
2711 if (ParseCmpPredicate(PredVal, Opc) ||
2712 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2713 ParseGlobalTypeAndValue(Val0) ||
2714 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2715 ParseGlobalTypeAndValue(Val1) ||
2716 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2717 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002718
Chris Lattnerac161bf2009-01-02 07:01:27 +00002719 if (Val0->getType() != Val1->getType())
2720 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002721
Chris Lattnerac161bf2009-01-02 07:01:27 +00002722 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002723
Chris Lattnerac161bf2009-01-02 07:01:27 +00002724 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002725 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002726 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002727 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002728 } else {
2729 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002730 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002731 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002732 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002733 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002734 }
2735 ID.Kind = ValID::t_Constant;
2736 return false;
2737 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002738
Chris Lattnerac161bf2009-01-02 07:01:27 +00002739 // Binary Operators.
2740 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002741 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002742 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002743 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002744 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002745 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002746 case lltok::kw_udiv:
2747 case lltok::kw_sdiv:
2748 case lltok::kw_fdiv:
2749 case lltok::kw_urem:
2750 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002751 case lltok::kw_frem:
2752 case lltok::kw_shl:
2753 case lltok::kw_lshr:
2754 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002755 bool NUW = false;
2756 bool NSW = false;
2757 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002758 unsigned Opc = Lex.getUIntVal();
2759 Constant *Val0, *Val1;
2760 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002761 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002762 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2763 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002764 if (EatIfPresent(lltok::kw_nuw))
2765 NUW = true;
2766 if (EatIfPresent(lltok::kw_nsw)) {
2767 NSW = true;
2768 if (EatIfPresent(lltok::kw_nuw))
2769 NUW = true;
2770 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002771 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2772 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002773 if (EatIfPresent(lltok::kw_exact))
2774 Exact = true;
2775 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002776 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2777 ParseGlobalTypeAndValue(Val0) ||
2778 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2779 ParseGlobalTypeAndValue(Val1) ||
2780 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2781 return true;
2782 if (Val0->getType() != Val1->getType())
2783 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002784 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002785 if (NUW)
2786 return Error(ModifierLoc, "nuw only applies to integer operations");
2787 if (NSW)
2788 return Error(ModifierLoc, "nsw only applies to integer operations");
2789 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002790 // Check that the type is valid for the operator.
2791 switch (Opc) {
2792 case Instruction::Add:
2793 case Instruction::Sub:
2794 case Instruction::Mul:
2795 case Instruction::UDiv:
2796 case Instruction::SDiv:
2797 case Instruction::URem:
2798 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002799 case Instruction::Shl:
2800 case Instruction::AShr:
2801 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002802 if (!Val0->getType()->isIntOrIntVectorTy())
2803 return Error(ID.Loc, "constexpr requires integer operands");
2804 break;
2805 case Instruction::FAdd:
2806 case Instruction::FSub:
2807 case Instruction::FMul:
2808 case Instruction::FDiv:
2809 case Instruction::FRem:
2810 if (!Val0->getType()->isFPOrFPVectorTy())
2811 return Error(ID.Loc, "constexpr requires fp operands");
2812 break;
2813 default: llvm_unreachable("Unknown binary operator!");
2814 }
Dan Gohman1b849082009-09-07 23:54:19 +00002815 unsigned Flags = 0;
2816 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2817 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002818 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002819 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002820 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002821 ID.Kind = ValID::t_Constant;
2822 return false;
2823 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002824
Chris Lattnerac161bf2009-01-02 07:01:27 +00002825 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002826 case lltok::kw_and:
2827 case lltok::kw_or:
2828 case lltok::kw_xor: {
2829 unsigned Opc = Lex.getUIntVal();
2830 Constant *Val0, *Val1;
2831 Lex.Lex();
2832 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2833 ParseGlobalTypeAndValue(Val0) ||
2834 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2835 ParseGlobalTypeAndValue(Val1) ||
2836 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2837 return true;
2838 if (Val0->getType() != Val1->getType())
2839 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002840 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002841 return Error(ID.Loc,
2842 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002843 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002844 ID.Kind = ValID::t_Constant;
2845 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002846 }
2847
Chris Lattnerac161bf2009-01-02 07:01:27 +00002848 case lltok::kw_getelementptr:
2849 case lltok::kw_shufflevector:
2850 case lltok::kw_insertelement:
2851 case lltok::kw_extractelement:
2852 case lltok::kw_select: {
2853 unsigned Opc = Lex.getUIntVal();
2854 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002855 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00002856 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002857 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00002858
Dan Gohman1639c392009-07-27 21:53:46 +00002859 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002860 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00002861
2862 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2863 return true;
2864
2865 LocTy ExplicitTypeLoc = Lex.getLoc();
2866 if (Opc == Instruction::GetElementPtr) {
2867 if (ParseType(Ty) ||
2868 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2869 return true;
2870 }
2871
2872 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002873 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2874 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002875
Chris Lattnerac161bf2009-01-02 07:01:27 +00002876 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002877 if (Elts.size() == 0 ||
2878 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00002879 return Error(ID.Loc, "base of getelementptr must be a pointer");
2880
2881 Type *BaseType = Elts[0]->getType();
2882 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00002883 if (Ty != BasePointerType->getElementType())
2884 return Error(
2885 ExplicitTypeLoc,
2886 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002887
Jay Foaded8db7d2011-07-21 14:31:17 +00002888 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00002889 for (Constant *Val : Indices) {
2890 Type *ValTy = Val->getType();
2891 if (!ValTy->getScalarType()->isIntegerTy())
2892 return Error(ID.Loc, "getelementptr index must be an integer");
2893 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2894 return Error(ID.Loc, "getelementptr index type missmatch");
2895 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00002896 unsigned ValNumEl = ValTy->getVectorNumElements();
2897 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00002898 if (ValNumEl != PtrNumEl)
2899 return Error(
2900 ID.Loc,
2901 "getelementptr vector index has a wrong number of elements");
2902 }
2903 }
2904
Owen Andersone90f9922015-03-10 06:34:57 +00002905 SmallPtrSet<const Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00002906 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00002907 return Error(ID.Loc, "base element of getelementptr must be sized");
2908
David Blaikie4a2e73b2015-04-02 18:55:32 +00002909 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00002910 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002911 ID.ConstantVal =
2912 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002913 } else if (Opc == Instruction::Select) {
2914 if (Elts.size() != 3)
2915 return Error(ID.Loc, "expected three operands to select");
2916 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2917 Elts[2]))
2918 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002919 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002920 } else if (Opc == Instruction::ShuffleVector) {
2921 if (Elts.size() != 3)
2922 return Error(ID.Loc, "expected three operands to shufflevector");
2923 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2924 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002925 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002926 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002927 } else if (Opc == Instruction::ExtractElement) {
2928 if (Elts.size() != 2)
2929 return Error(ID.Loc, "expected two operands to extractelement");
2930 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2931 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002932 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002933 } else {
2934 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2935 if (Elts.size() != 3)
2936 return Error(ID.Loc, "expected three operands to insertelement");
2937 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2938 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002939 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002940 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002941 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002942
Chris Lattnerac161bf2009-01-02 07:01:27 +00002943 ID.Kind = ValID::t_Constant;
2944 return false;
2945 }
2946 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002947
Chris Lattnerac161bf2009-01-02 07:01:27 +00002948 Lex.Lex();
2949 return false;
2950}
2951
2952/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002953bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002954 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002955 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002956 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002957 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002958 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002959 if (V && !(C = dyn_cast<Constant>(V)))
2960 return Error(ID.Loc, "global values must be constants");
2961 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002962}
2963
Victor Hernandez9d75c962010-01-11 22:31:58 +00002964bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002965 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002966 return ParseType(Ty) ||
2967 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002968}
2969
Rafael Espindola83a362c2015-01-06 22:55:16 +00002970bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002971 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002972
2973 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002974 if (!EatIfPresent(lltok::kw_comdat))
2975 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002976
2977 if (EatIfPresent(lltok::lparen)) {
2978 if (Lex.getKind() != lltok::ComdatVar)
2979 return TokError("expected comdat variable");
2980 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2981 Lex.Lex();
2982 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2983 return true;
2984 } else {
2985 if (GlobalName.empty())
2986 return TokError("comdat cannot be unnamed");
2987 C = getComdat(GlobalName, KwLoc);
2988 }
2989
David Majnemerdad0a642014-06-27 18:19:56 +00002990 return false;
2991}
2992
Victor Hernandez9d75c962010-01-11 22:31:58 +00002993/// ParseGlobalValueVector
2994/// ::= /*empty*/
2995/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002996bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002997 // Empty list.
2998 if (Lex.getKind() == lltok::rbrace ||
2999 Lex.getKind() == lltok::rsquare ||
3000 Lex.getKind() == lltok::greater ||
3001 Lex.getKind() == lltok::rparen)
3002 return false;
3003
3004 Constant *C;
3005 if (ParseGlobalTypeAndValue(C)) return true;
3006 Elts.push_back(C);
3007
3008 while (EatIfPresent(lltok::comma)) {
3009 if (ParseGlobalTypeAndValue(C)) return true;
3010 Elts.push_back(C);
3011 }
3012
3013 return false;
3014}
3015
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003016bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003017 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003018 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003019 return true;
3020
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003021 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003022 return false;
3023}
3024
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003025/// MDNode:
3026/// ::= !{ ... }
3027/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003028/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003029bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003030 if (Lex.getKind() == lltok::MetadataVar)
3031 return ParseSpecializedMDNode(N);
3032
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003033 return ParseToken(lltok::exclaim, "expected '!' here") ||
3034 ParseMDNodeTail(N);
3035}
3036
3037bool LLParser::ParseMDNodeTail(MDNode *&N) {
3038 // !{ ... }
3039 if (Lex.getKind() == lltok::lbrace)
3040 return ParseMDTuple(N);
3041
3042 // !42
3043 return ParseMDNodeID(N);
3044}
3045
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003046namespace {
3047
3048/// Structure to represent an optional metadata field.
3049template <class FieldTy> struct MDFieldImpl {
3050 typedef MDFieldImpl ImplTy;
3051 FieldTy Val;
3052 bool Seen;
3053
3054 void assign(FieldTy Val) {
3055 Seen = true;
3056 this->Val = std::move(Val);
3057 }
3058
3059 explicit MDFieldImpl(FieldTy Default)
3060 : Val(std::move(Default)), Seen(false) {}
3061};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003062
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003063struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3064 uint64_t Max;
3065
3066 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3067 : ImplTy(Default), Max(Max) {}
3068};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003069struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003070 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003071};
3072struct ColumnField : public MDUnsignedField {
3073 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3074};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003075struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003076 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003077 DwarfTagField(dwarf::Tag DefaultTag)
3078 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003079};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003080struct DwarfAttEncodingField : public MDUnsignedField {
3081 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3082};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003083struct DwarfVirtualityField : public MDUnsignedField {
3084 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3085};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003086struct DwarfLangField : public MDUnsignedField {
3087 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3088};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003089
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003090struct DIFlagField : public MDUnsignedField {
3091 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3092};
3093
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003094struct MDSignedField : public MDFieldImpl<int64_t> {
3095 int64_t Min;
3096 int64_t Max;
3097
3098 MDSignedField(int64_t Default = 0)
3099 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3100 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3101 : ImplTy(Default), Min(Min), Max(Max) {}
3102};
3103
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003104struct MDBoolField : public MDFieldImpl<bool> {
3105 MDBoolField(bool Default = false) : ImplTy(Default) {}
3106};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003107struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003108 bool AllowNull;
3109
3110 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003111};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003112struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3113 MDConstant() : ImplTy(nullptr) {}
3114};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003115struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003116 bool AllowEmpty;
3117 MDStringField(bool AllowEmpty = true)
3118 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003119};
3120struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3121 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3122};
3123
3124} // end namespace
3125
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003126namespace llvm {
3127
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003128template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003129bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003130 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003131 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3132 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003133
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003134 auto &U = Lex.getAPSIntVal();
3135 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003136 return TokError("value for '" + Name + "' too large, limit is " +
3137 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003138 Result.assign(U.getZExtValue());
3139 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003140 Lex.Lex();
3141 return false;
3142}
3143
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003144template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003145bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3146 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3147}
3148template <>
3149bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3150 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3151}
3152
3153template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003154bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3155 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003156 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003157
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003158 if (Lex.getKind() != lltok::DwarfTag)
3159 return TokError("expected DWARF tag");
3160
3161 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3162 if (Tag == dwarf::DW_TAG_invalid)
3163 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003164 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003165
3166 Result.assign(Tag);
3167 Lex.Lex();
3168 return false;
3169}
3170
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003171template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003172bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3173 DwarfVirtualityField &Result) {
3174 if (Lex.getKind() == lltok::APSInt)
3175 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3176
3177 if (Lex.getKind() != lltok::DwarfVirtuality)
3178 return TokError("expected DWARF virtuality code");
3179
3180 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3181 if (!Virtuality)
3182 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3183 Lex.getStrVal() + "'");
3184 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3185 Result.assign(Virtuality);
3186 Lex.Lex();
3187 return false;
3188}
3189
3190template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003191bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3192 if (Lex.getKind() == lltok::APSInt)
3193 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3194
3195 if (Lex.getKind() != lltok::DwarfLang)
3196 return TokError("expected DWARF language");
3197
3198 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3199 if (!Lang)
3200 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3201 "'");
3202 assert(Lang <= Result.Max && "Expected valid DWARF language");
3203 Result.assign(Lang);
3204 Lex.Lex();
3205 return false;
3206}
3207
3208template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003209bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003210 DwarfAttEncodingField &Result) {
3211 if (Lex.getKind() == lltok::APSInt)
3212 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3213
3214 if (Lex.getKind() != lltok::DwarfAttEncoding)
3215 return TokError("expected DWARF type attribute encoding");
3216
3217 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3218 if (!Encoding)
3219 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3220 Lex.getStrVal() + "'");
3221 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3222 Result.assign(Encoding);
3223 Lex.Lex();
3224 return false;
3225}
3226
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003227/// DIFlagField
3228/// ::= uint32
3229/// ::= DIFlagVector
3230/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3231template <>
3232bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3233 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3234
3235 // Parser for a single flag.
3236 auto parseFlag = [&](unsigned &Val) {
3237 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3238 return ParseUInt32(Val);
3239
3240 if (Lex.getKind() != lltok::DIFlag)
3241 return TokError("expected debug info flag");
3242
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003243 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003244 if (!Val)
3245 return TokError(Twine("invalid debug info flag flag '") +
3246 Lex.getStrVal() + "'");
3247 Lex.Lex();
3248 return false;
3249 };
3250
3251 // Parse the flags and combine them together.
3252 unsigned Combined = 0;
3253 do {
3254 unsigned Val;
3255 if (parseFlag(Val))
3256 return true;
3257 Combined |= Val;
3258 } while (EatIfPresent(lltok::bar));
3259
3260 Result.assign(Combined);
3261 return false;
3262}
3263
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003264template <>
3265bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003266 MDSignedField &Result) {
3267 if (Lex.getKind() != lltok::APSInt)
3268 return TokError("expected signed integer");
3269
3270 auto &S = Lex.getAPSIntVal();
3271 if (S < Result.Min)
3272 return TokError("value for '" + Name + "' too small, limit is " +
3273 Twine(Result.Min));
3274 if (S > Result.Max)
3275 return TokError("value for '" + Name + "' too large, limit is " +
3276 Twine(Result.Max));
3277 Result.assign(S.getExtValue());
3278 assert(Result.Val >= Result.Min && "Expected value in range");
3279 assert(Result.Val <= Result.Max && "Expected value in range");
3280 Lex.Lex();
3281 return false;
3282}
3283
3284template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003285bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3286 switch (Lex.getKind()) {
3287 default:
3288 return TokError("expected 'true' or 'false'");
3289 case lltok::kw_true:
3290 Result.assign(true);
3291 break;
3292 case lltok::kw_false:
3293 Result.assign(false);
3294 break;
3295 }
3296 Lex.Lex();
3297 return false;
3298}
3299
3300template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003301bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003302 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003303 if (!Result.AllowNull)
3304 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003305 Lex.Lex();
3306 Result.assign(nullptr);
3307 return false;
3308 }
3309
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003310 Metadata *MD;
3311 if (ParseMetadata(MD, nullptr))
3312 return true;
3313
3314 Result.assign(MD);
3315 return false;
3316}
3317
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003318template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003319bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3320 Metadata *MD;
3321 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3322 return true;
3323
3324 Result.assign(cast<ConstantAsMetadata>(MD));
3325 return false;
3326}
3327
3328template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003329bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003330 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003331 std::string S;
3332 if (ParseStringConstant(S))
3333 return true;
3334
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003335 if (!Result.AllowEmpty && S.empty())
3336 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3337
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003338 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003339 return false;
3340}
3341
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003342template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003343bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3344 SmallVector<Metadata *, 4> MDs;
3345 if (ParseMDNodeVector(MDs))
3346 return true;
3347
3348 Result.assign(std::move(MDs));
3349 return false;
3350}
3351
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003352} // end namespace llvm
3353
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003354template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003355bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003356 do {
3357 if (Lex.getKind() != lltok::LabelStr)
3358 return TokError("expected field label here");
3359
3360 if (parseField())
3361 return true;
3362 } while (EatIfPresent(lltok::comma));
3363
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003364 return false;
3365}
3366
3367template <class ParserTy>
3368bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3369 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3370 Lex.Lex();
3371
3372 if (ParseToken(lltok::lparen, "expected '(' here"))
3373 return true;
3374 if (Lex.getKind() != lltok::rparen)
3375 if (ParseMDFieldsImplBody(parseField))
3376 return true;
3377
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003378 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003379 return ParseToken(lltok::rparen, "expected ')' here");
3380}
3381
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003382template <class FieldTy>
3383bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3384 if (Result.Seen)
3385 return TokError("field '" + Name + "' cannot be specified more than once");
3386
3387 LocTy Loc = Lex.getLoc();
3388 Lex.Lex();
3389 return ParseMDField(Loc, Name, Result);
3390}
3391
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003392bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3393 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003394
3395#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003396 if (Lex.getStrVal() == #CLASS) \
3397 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003398#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003399
3400 return TokError("expected metadata type");
3401}
3402
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003403#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3404#define NOP_FIELD(NAME, TYPE, INIT)
3405#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3406 if (!NAME.Seen) \
3407 return Error(ClosingLoc, "missing required field '" #NAME "'");
3408#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003409 if (Lex.getStrVal() == #NAME) \
3410 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003411#define PARSE_MD_FIELDS() \
3412 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3413 do { \
3414 LocTy ClosingLoc; \
3415 if (ParseMDFieldsImpl([&]() -> bool { \
3416 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3417 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3418 }, ClosingLoc)) \
3419 return true; \
3420 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3421 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003422#define GET_OR_DISTINCT(CLASS, ARGS) \
3423 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003424
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003425/// ParseDILocationFields:
3426/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3427bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003428#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003429 OPTIONAL(line, LineField, ); \
3430 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003431 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003432 OPTIONAL(inlinedAt, MDField, );
3433 PARSE_MD_FIELDS();
3434#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003435
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003436 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003437 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003438 return false;
3439}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003440
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003441/// ParseGenericDINode:
3442/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3443bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003444#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003445 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003446 OPTIONAL(header, MDStringField, ); \
3447 OPTIONAL(operands, MDFieldList, );
3448 PARSE_MD_FIELDS();
3449#undef VISIT_MD_FIELDS
3450
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003451 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003452 (Context, tag.Val, header.Val, operands.Val));
3453 return false;
3454}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003455
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003456/// ParseDISubrange:
3457/// ::= !DISubrange(count: 30, lowerBound: 2)
3458bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003459#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003460 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003461 OPTIONAL(lowerBound, MDSignedField, );
3462 PARSE_MD_FIELDS();
3463#undef VISIT_MD_FIELDS
3464
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003465 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003466 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003467}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003468
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003469/// ParseDIEnumerator:
3470/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3471bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003472#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003473 REQUIRED(name, MDStringField, ); \
3474 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003475 PARSE_MD_FIELDS();
3476#undef VISIT_MD_FIELDS
3477
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003478 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003479 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003480}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003481
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003482/// ParseDIBasicType:
3483/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3484bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003485#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003486 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003487 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003488 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3489 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003490 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003491 PARSE_MD_FIELDS();
3492#undef VISIT_MD_FIELDS
3493
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003494 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003495 align.Val, encoding.Val));
3496 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003497}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003498
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003499/// ParseDIDerivedType:
3500/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003501/// line: 7, scope: !1, baseType: !2, size: 32,
3502/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003503bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003504#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3505 REQUIRED(tag, DwarfTagField, ); \
3506 OPTIONAL(name, MDStringField, ); \
3507 OPTIONAL(file, MDField, ); \
3508 OPTIONAL(line, LineField, ); \
3509 OPTIONAL(scope, MDField, ); \
3510 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003511 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3512 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3513 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003514 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003515 OPTIONAL(extraData, MDField, );
3516 PARSE_MD_FIELDS();
3517#undef VISIT_MD_FIELDS
3518
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003519 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003520 (Context, tag.Val, name.Val, file.Val, line.Val,
3521 scope.Val, baseType.Val, size.Val, align.Val,
3522 offset.Val, flags.Val, extraData.Val));
3523 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003524}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003525
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003526bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003527#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3528 REQUIRED(tag, DwarfTagField, ); \
3529 OPTIONAL(name, MDStringField, ); \
3530 OPTIONAL(file, MDField, ); \
3531 OPTIONAL(line, LineField, ); \
3532 OPTIONAL(scope, MDField, ); \
3533 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003534 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3535 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3536 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003537 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003538 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003539 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003540 OPTIONAL(vtableHolder, MDField, ); \
3541 OPTIONAL(templateParams, MDField, ); \
3542 OPTIONAL(identifier, MDStringField, );
3543 PARSE_MD_FIELDS();
3544#undef VISIT_MD_FIELDS
3545
3546 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003547 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003548 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3549 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3550 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3551 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003552}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003553
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003554bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003555#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003556 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003557 REQUIRED(types, MDField, );
3558 PARSE_MD_FIELDS();
3559#undef VISIT_MD_FIELDS
3560
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003561 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003562 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003563}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003564
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003565/// ParseDIFileType:
3566/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3567bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003568#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3569 REQUIRED(filename, MDStringField, ); \
3570 REQUIRED(directory, MDStringField, );
3571 PARSE_MD_FIELDS();
3572#undef VISIT_MD_FIELDS
3573
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003574 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003575 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003576}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003577
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003578/// ParseDICompileUnit:
3579/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003580/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3581/// splitDebugFilename: "abc.debug", emissionKind: 1,
3582/// enums: !1, retainedTypes: !2, subprograms: !3,
Adrian Prantl1f599f92015-05-21 20:37:30 +00003583/// globals: !4, imports: !5, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003584bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003585#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3586 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003587 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003588 OPTIONAL(producer, MDStringField, ); \
3589 OPTIONAL(isOptimized, MDBoolField, ); \
3590 OPTIONAL(flags, MDStringField, ); \
3591 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3592 OPTIONAL(splitDebugFilename, MDStringField, ); \
3593 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3594 OPTIONAL(enums, MDField, ); \
3595 OPTIONAL(retainedTypes, MDField, ); \
3596 OPTIONAL(subprograms, MDField, ); \
3597 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003598 OPTIONAL(imports, MDField, ); \
3599 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003600 PARSE_MD_FIELDS();
3601#undef VISIT_MD_FIELDS
3602
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003603 Result = GET_OR_DISTINCT(DICompileUnit,
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003604 (Context, language.Val, file.Val, producer.Val,
3605 isOptimized.Val, flags.Val, runtimeVersion.Val,
3606 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3607 retainedTypes.Val, subprograms.Val, globals.Val,
Adrian Prantl1f599f92015-05-21 20:37:30 +00003608 imports.Val, dwoId.Val));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003609 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003610}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003611
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003612/// ParseDISubprogram:
3613/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003614/// file: !1, line: 7, type: !2, isLocal: false,
3615/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003616/// virtuality: DW_VIRTUALTIY_pure_virtual,
3617/// virtualIndex: 10, flags: 11,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003618/// isOptimized: false, function: void ()* @_Z3foov,
3619/// templateParams: !4, declaration: !5, variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003620bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003621#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3622 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003623 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003624 OPTIONAL(linkageName, MDStringField, ); \
3625 OPTIONAL(file, MDField, ); \
3626 OPTIONAL(line, LineField, ); \
3627 OPTIONAL(type, MDField, ); \
3628 OPTIONAL(isLocal, MDBoolField, ); \
3629 OPTIONAL(isDefinition, MDBoolField, (true)); \
3630 OPTIONAL(scopeLine, LineField, ); \
3631 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003632 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003633 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003634 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003635 OPTIONAL(isOptimized, MDBoolField, ); \
3636 OPTIONAL(function, MDConstant, ); \
3637 OPTIONAL(templateParams, MDField, ); \
3638 OPTIONAL(declaration, MDField, ); \
3639 OPTIONAL(variables, MDField, );
3640 PARSE_MD_FIELDS();
3641#undef VISIT_MD_FIELDS
3642
3643 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003644 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003645 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3646 scopeLine.Val, containingType.Val, virtuality.Val,
3647 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3648 templateParams.Val, declaration.Val, variables.Val));
3649 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003650}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003651
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003652/// ParseDILexicalBlock:
3653/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3654bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003655#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003656 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003657 OPTIONAL(file, MDField, ); \
3658 OPTIONAL(line, LineField, ); \
3659 OPTIONAL(column, ColumnField, );
3660 PARSE_MD_FIELDS();
3661#undef VISIT_MD_FIELDS
3662
3663 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003664 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003665 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003666}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003667
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003668/// ParseDILexicalBlockFile:
3669/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3670bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003671#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003672 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003673 OPTIONAL(file, MDField, ); \
3674 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3675 PARSE_MD_FIELDS();
3676#undef VISIT_MD_FIELDS
3677
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003678 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003679 (Context, scope.Val, file.Val, discriminator.Val));
3680 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003681}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003682
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003683/// ParseDINamespace:
3684/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3685bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003686#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3687 REQUIRED(scope, MDField, ); \
3688 OPTIONAL(file, MDField, ); \
3689 OPTIONAL(name, MDStringField, ); \
3690 OPTIONAL(line, LineField, );
3691 PARSE_MD_FIELDS();
3692#undef VISIT_MD_FIELDS
3693
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003694 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003695 (Context, scope.Val, file.Val, name.Val, line.Val));
3696 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003697}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003698
Adrian Prantlab1243f2015-06-29 23:03:47 +00003699/// ParseDIModule:
3700/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3701/// includePath: "/usr/include", isysroot: "/")
3702bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3703#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3704 REQUIRED(scope, MDField, ); \
3705 REQUIRED(name, MDStringField, ); \
3706 OPTIONAL(configMacros, MDStringField, ); \
3707 OPTIONAL(includePath, MDStringField, ); \
3708 OPTIONAL(isysroot, MDStringField, );
3709 PARSE_MD_FIELDS();
3710#undef VISIT_MD_FIELDS
3711
3712 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3713 configMacros.Val, includePath.Val, isysroot.Val));
3714 return false;
3715}
3716
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003717/// ParseDITemplateTypeParameter:
3718/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3719bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003720#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003721 OPTIONAL(name, MDStringField, ); \
3722 REQUIRED(type, MDField, );
3723 PARSE_MD_FIELDS();
3724#undef VISIT_MD_FIELDS
3725
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003726 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003727 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003728 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003729}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003730
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003731/// ParseDITemplateValueParameter:
3732/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003733/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003734bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003735#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003736 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003737 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003738 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003739 REQUIRED(value, MDField, );
3740 PARSE_MD_FIELDS();
3741#undef VISIT_MD_FIELDS
3742
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003743 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003744 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003745 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003746}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003747
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003748/// ParseDIGlobalVariable:
3749/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003750/// file: !1, line: 7, type: !2, isLocal: false,
3751/// isDefinition: true, variable: i32* @foo,
3752/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003753bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003754#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003755 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003756 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003757 OPTIONAL(linkageName, MDStringField, ); \
3758 OPTIONAL(file, MDField, ); \
3759 OPTIONAL(line, LineField, ); \
3760 OPTIONAL(type, MDField, ); \
3761 OPTIONAL(isLocal, MDBoolField, ); \
3762 OPTIONAL(isDefinition, MDBoolField, (true)); \
3763 OPTIONAL(variable, MDConstant, ); \
3764 OPTIONAL(declaration, MDField, );
3765 PARSE_MD_FIELDS();
3766#undef VISIT_MD_FIELDS
3767
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003768 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003769 (Context, scope.Val, name.Val, linkageName.Val,
3770 file.Val, line.Val, type.Val, isLocal.Val,
3771 isDefinition.Val, variable.Val, declaration.Val));
3772 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003773}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003774
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003775/// ParseDILocalVariable:
3776/// ::= !DILocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003777/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003778bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003779#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3780 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003781 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003782 OPTIONAL(name, MDStringField, ); \
3783 OPTIONAL(file, MDField, ); \
3784 OPTIONAL(line, LineField, ); \
3785 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith69488692015-06-02 17:17:44 +00003786 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003787 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003788 PARSE_MD_FIELDS();
3789#undef VISIT_MD_FIELDS
3790
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003791 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003792 (Context, tag.Val, scope.Val, name.Val, file.Val,
3793 line.Val, type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003794 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003795}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003796
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003797/// ParseDIExpression:
3798/// ::= !DIExpression(0, 7, -1)
3799bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003800 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3801 Lex.Lex();
3802
3803 if (ParseToken(lltok::lparen, "expected '(' here"))
3804 return true;
3805
3806 SmallVector<uint64_t, 8> Elements;
3807 if (Lex.getKind() != lltok::rparen)
3808 do {
3809 if (Lex.getKind() == lltok::DwarfOp) {
3810 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3811 Lex.Lex();
3812 Elements.push_back(Op);
3813 continue;
3814 }
3815 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3816 }
3817
3818 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3819 return TokError("expected unsigned integer");
3820
3821 auto &U = Lex.getAPSIntVal();
3822 if (U.ugt(UINT64_MAX))
3823 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3824 Elements.push_back(U.getZExtValue());
3825 Lex.Lex();
3826 } while (EatIfPresent(lltok::comma));
3827
3828 if (ParseToken(lltok::rparen, "expected ')' here"))
3829 return true;
3830
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003831 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003832 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003833}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003834
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003835/// ParseDIObjCProperty:
3836/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003837/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003838bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003839#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003840 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003841 OPTIONAL(file, MDField, ); \
3842 OPTIONAL(line, LineField, ); \
3843 OPTIONAL(setter, MDStringField, ); \
3844 OPTIONAL(getter, MDStringField, ); \
3845 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3846 OPTIONAL(type, MDField, );
3847 PARSE_MD_FIELDS();
3848#undef VISIT_MD_FIELDS
3849
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003850 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003851 (Context, name.Val, file.Val, line.Val, setter.Val,
3852 getter.Val, attributes.Val, type.Val));
3853 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003854}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003855
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003856/// ParseDIImportedEntity:
3857/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003858/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003859bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003860#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3861 REQUIRED(tag, DwarfTagField, ); \
3862 REQUIRED(scope, MDField, ); \
3863 OPTIONAL(entity, MDField, ); \
3864 OPTIONAL(line, LineField, ); \
3865 OPTIONAL(name, MDStringField, );
3866 PARSE_MD_FIELDS();
3867#undef VISIT_MD_FIELDS
3868
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003869 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003870 entity.Val, line.Val, name.Val));
3871 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003872}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003873
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003874#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003875#undef NOP_FIELD
3876#undef REQUIRE_FIELD
3877#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003878
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003879/// ParseMetadataAsValue
3880/// ::= metadata i32 %local
3881/// ::= metadata i32 @global
3882/// ::= metadata i32 7
3883/// ::= metadata !0
3884/// ::= metadata !{...}
3885/// ::= metadata !"string"
3886bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3887 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003888 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003889 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003890 return true;
3891
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003892 V = MetadataAsValue::get(Context, MD);
3893 return false;
3894}
3895
3896/// ParseValueAsMetadata
3897/// ::= i32 %local
3898/// ::= i32 @global
3899/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003900bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3901 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003902 Type *Ty;
3903 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003904 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003905 return true;
3906 if (Ty->isMetadataTy())
3907 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3908
3909 Value *V;
3910 if (ParseValue(Ty, V, PFS))
3911 return true;
3912
3913 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003914 return false;
3915}
3916
3917/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003918/// ::= i32 %local
3919/// ::= i32 @global
3920/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00003921/// ::= !42
3922/// ::= !{...}
3923/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003924/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003925bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003926 if (Lex.getKind() == lltok::MetadataVar) {
3927 MDNode *N;
3928 if (ParseSpecializedMDNode(N))
3929 return true;
3930 MD = N;
3931 return false;
3932 }
3933
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003934 // ValueAsMetadata:
3935 // <type> <value>
3936 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003937 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003938
3939 // '!'.
3940 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3941 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00003942
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003943 // MDString:
3944 // ::= '!' STRINGCONSTANT
3945 if (Lex.getKind() == lltok::StringConstant) {
3946 MDString *S;
3947 if (ParseMDString(S))
3948 return true;
3949 MD = S;
3950 return false;
3951 }
3952
Dan Gohman8939ba332010-07-14 18:26:50 +00003953 // MDNode:
3954 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003955 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003956 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003957 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003958 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003959 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003960 return false;
3961}
3962
Victor Hernandez9d75c962010-01-11 22:31:58 +00003963
3964//===----------------------------------------------------------------------===//
3965// Function Parsing.
3966//===----------------------------------------------------------------------===//
3967
Chris Lattner229907c2011-07-18 04:54:35 +00003968bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003969 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003970 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003971 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003972
Chris Lattnerac161bf2009-01-02 07:01:27 +00003973 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003974 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003975 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3976 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003977 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003978 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003979 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3980 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003981 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003982 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003983 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003984 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003985 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003986 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3987 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003988 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003989 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003990 return false;
3991 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003992 case ValID::t_GlobalName:
3993 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003994 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003995 case ValID::t_GlobalID:
3996 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003997 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003998 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003999 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004000 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004001 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004002 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004003 return false;
4004 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004005 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004006 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4007 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004008
Dan Gohman518cda42011-12-17 00:04:22 +00004009 // The lexer has no type info, so builds all half, float, and double FP
4010 // constants as double. Fix this here. Long double does not need this.
4011 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004012 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004013 if (Ty->isHalfTy())
4014 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4015 &Ignored);
4016 else if (Ty->isFloatTy())
4017 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4018 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004019 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004020 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004021
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004022 if (V->getType() != Ty)
4023 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004024 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004025
Chris Lattnerac161bf2009-01-02 07:01:27 +00004026 return false;
4027 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004028 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004029 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004030 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004031 return false;
4032 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004033 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004034 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004035 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004036 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004037 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004038 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004039 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004040 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004041 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004042 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004043 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004044 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004045 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004046 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004047 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004048 return false;
4049 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004050 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004051 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004052
Chris Lattnerac161bf2009-01-02 07:01:27 +00004053 V = ID.ConstantVal;
4054 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004055 case ValID::t_ConstantStruct:
4056 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004057 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004058 if (ST->getNumElements() != ID.UIntVal)
4059 return Error(ID.Loc,
4060 "initializer with struct type has wrong # elements");
4061 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4062 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004063
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004064 // Verify that the elements are compatible with the structtype.
4065 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4066 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4067 return Error(ID.Loc, "element " + Twine(i) +
4068 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004069
Reid Kleckner2ae03e12015-03-04 18:31:10 +00004070 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4071 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004072 } else
4073 return Error(ID.Loc, "constant expression type mismatch");
4074 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004075 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004076 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004077}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004078
Alex Lorenzd2255952015-07-17 22:07:03 +00004079bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4080 C = nullptr;
4081 ValID ID;
4082 auto Loc = Lex.getLoc();
4083 if (ParseValID(ID, /*PFS=*/nullptr))
4084 return true;
4085 switch (ID.Kind) {
4086 case ValID::t_APSInt:
4087 case ValID::t_APFloat:
4088 case ValID::t_Constant:
4089 case ValID::t_ConstantStruct:
4090 case ValID::t_PackedConstantStruct: {
4091 Value *V;
4092 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4093 return true;
4094 assert(isa<Constant>(V) && "Expected a constant value");
4095 C = cast<Constant>(V);
4096 return false;
4097 }
4098 default:
4099 return Error(Loc, "expected a constant value");
4100 }
4101}
4102
Chris Lattner229907c2011-07-18 04:54:35 +00004103bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004104 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004105 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004106 return ParseValID(ID, PFS) ||
4107 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004108}
4109
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004110bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004111 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004112 return ParseType(Ty) ||
4113 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004114}
4115
Chris Lattner3ed871f2009-10-27 19:13:16 +00004116bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4117 PerFunctionState &PFS) {
4118 Value *V;
4119 Loc = Lex.getLoc();
4120 if (ParseTypeAndValue(V, PFS)) return true;
4121 if (!isa<BasicBlock>(V))
4122 return Error(Loc, "expected a basic block");
4123 BB = cast<BasicBlock>(V);
4124 return false;
4125}
4126
4127
Chris Lattnerac161bf2009-01-02 07:01:27 +00004128/// FunctionHeader
4129/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004130/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004131/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004132bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4133 // Parse the linkage.
4134 LocTy LinkageLoc = Lex.getLoc();
4135 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004136
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004137 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004138 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004139 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004140 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004141 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004142 LocTy RetTypeLoc = Lex.getLoc();
4143 if (ParseOptionalLinkage(Linkage) ||
4144 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004145 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004146 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004147 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004148 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004149 return true;
4150
4151 // Verify that the linkage is ok.
4152 switch ((GlobalValue::LinkageTypes)Linkage) {
4153 case GlobalValue::ExternalLinkage:
4154 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004155 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004156 if (isDefine)
4157 return Error(LinkageLoc, "invalid linkage for function definition");
4158 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004159 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004160 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004161 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004162 case GlobalValue::LinkOnceAnyLinkage:
4163 case GlobalValue::LinkOnceODRLinkage:
4164 case GlobalValue::WeakAnyLinkage:
4165 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004166 if (!isDefine)
4167 return Error(LinkageLoc, "invalid linkage for function declaration");
4168 break;
4169 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004170 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004171 return Error(LinkageLoc, "invalid function linkage type");
4172 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004173
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004174 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4175 return Error(LinkageLoc,
4176 "symbol with local linkage must have default visibility");
4177
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004178 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004179 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004180
Chris Lattnerac161bf2009-01-02 07:01:27 +00004181 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004182
4183 std::string FunctionName;
4184 if (Lex.getKind() == lltok::GlobalVar) {
4185 FunctionName = Lex.getStrVal();
4186 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4187 unsigned NameID = Lex.getUIntVal();
4188
4189 if (NameID != NumberedVals.size())
4190 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004191 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004192 } else {
4193 return TokError("expected function name");
4194 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004195
Chris Lattner3822f632009-01-02 08:05:26 +00004196 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004197
Chris Lattner3822f632009-01-02 08:05:26 +00004198 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004199 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004200
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004201 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004202 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004203 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004204 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004205 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004206 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004207 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004208 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004209 bool UnnamedAddr;
4210 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004211 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004212 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004213 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004214 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004215
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004216 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004217 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4218 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004219 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004220 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004221 (EatIfPresent(lltok::kw_section) &&
4222 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004223 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004224 ParseOptionalAlignment(Alignment) ||
4225 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004226 ParseStringConstant(GC)) ||
4227 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004228 ParseGlobalTypeAndValue(Prefix)) ||
4229 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004230 ParseGlobalTypeAndValue(Prologue)) ||
4231 (EatIfPresent(lltok::kw_personality) &&
4232 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004233 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004234
Michael Gottesman41748d72013-06-27 00:25:01 +00004235 if (FuncAttrs.contains(Attribute::Builtin))
4236 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004237
Chris Lattnerac161bf2009-01-02 07:01:27 +00004238 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004239 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004240 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004241 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004242 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004243
Chris Lattnerac161bf2009-01-02 07:01:27 +00004244 // Okay, if we got here, the function is syntactically valid. Convert types
4245 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004246 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004247 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004248
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004249 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004250 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4251 AttributeSet::ReturnIndex,
4252 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004253
Chris Lattnerac161bf2009-01-02 07:01:27 +00004254 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004255 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004256 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4257 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004258 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4259 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004260 }
4261
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004262 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004263 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4264 AttributeSet::FunctionIndex,
4265 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004266
Bill Wendlinge94d8432012-12-07 23:16:57 +00004267 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004268
Bill Wendling749a43d2012-12-30 13:50:49 +00004269 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004270 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4271
Chris Lattner229907c2011-07-18 04:54:35 +00004272 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004273 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004274 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004275
Craig Topper2617dcc2014-04-15 06:32:26 +00004276 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004277 if (!FunctionName.empty()) {
4278 // If this was a definition of a forward reference, remove the definition
4279 // from the forward reference table and fill in the forward ref.
4280 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4281 ForwardRefVals.find(FunctionName);
4282 if (FRVI != ForwardRefVals.end()) {
4283 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004284 if (!Fn)
4285 return Error(FRVI->second.second, "invalid forward reference to "
4286 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004287 if (Fn->getType() != PFT)
4288 return Error(FRVI->second.second, "invalid forward reference to "
4289 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004290
Chris Lattnerac161bf2009-01-02 07:01:27 +00004291 ForwardRefVals.erase(FRVI);
4292 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004293 // Reject redefinitions.
4294 return Error(NameLoc, "invalid redefinition of function '" +
4295 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004296 } else if (M->getNamedValue(FunctionName)) {
4297 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004298 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004299
Dan Gohman399d6ae2009-08-29 23:37:49 +00004300 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004301 // If this is a definition of a forward referenced function, make sure the
4302 // types agree.
4303 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4304 = ForwardRefValIDs.find(NumberedVals.size());
4305 if (I != ForwardRefValIDs.end()) {
4306 Fn = cast<Function>(I->second.first);
4307 if (Fn->getType() != PFT)
4308 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004309 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004310 ForwardRefValIDs.erase(I);
4311 }
4312 }
4313
Craig Topper2617dcc2014-04-15 06:32:26 +00004314 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004315 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4316 else // Move the forward-reference to the correct spot in the module.
4317 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4318
4319 if (FunctionName.empty())
4320 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004321
Chris Lattnerac161bf2009-01-02 07:01:27 +00004322 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4323 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004324 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004325 Fn->setCallingConv(CC);
4326 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004327 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004328 Fn->setAlignment(Alignment);
4329 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004330 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004331 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004332 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004333 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004334 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004335 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004336
Chris Lattnerac161bf2009-01-02 07:01:27 +00004337 // Add all of the arguments we parsed to the function.
4338 Function::arg_iterator ArgIt = Fn->arg_begin();
4339 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4340 // If the argument has a name, insert it into the argument symbol table.
4341 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004342
Chris Lattnerac161bf2009-01-02 07:01:27 +00004343 // Set the name, if it conflicted, it will be auto-renamed.
4344 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004345
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004346 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004347 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4348 ArgList[i].Name + "'");
4349 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004350
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004351 if (isDefine)
4352 return false;
4353
Robin Morisset039781e2014-08-29 21:53:01 +00004354 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004355 ValID ID;
4356 if (FunctionName.empty()) {
4357 ID.Kind = ValID::t_GlobalID;
4358 ID.UIntVal = NumberedVals.size() - 1;
4359 } else {
4360 ID.Kind = ValID::t_GlobalName;
4361 ID.StrVal = FunctionName;
4362 }
4363 auto Blocks = ForwardRefBlockAddresses.find(ID);
4364 if (Blocks != ForwardRefBlockAddresses.end())
4365 return Error(Blocks->first.Loc,
4366 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004367 return false;
4368}
4369
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004370bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4371 ValID ID;
4372 if (FunctionNumber == -1) {
4373 ID.Kind = ValID::t_GlobalName;
4374 ID.StrVal = F.getName();
4375 } else {
4376 ID.Kind = ValID::t_GlobalID;
4377 ID.UIntVal = FunctionNumber;
4378 }
4379
4380 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4381 if (Blocks == P.ForwardRefBlockAddresses.end())
4382 return false;
4383
4384 for (const auto &I : Blocks->second) {
4385 const ValID &BBID = I.first;
4386 GlobalValue *GV = I.second;
4387
4388 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4389 "Expected local id or name");
4390 BasicBlock *BB;
4391 if (BBID.Kind == ValID::t_LocalName)
4392 BB = GetBB(BBID.StrVal, BBID.Loc);
4393 else
4394 BB = GetBB(BBID.UIntVal, BBID.Loc);
4395 if (!BB)
4396 return P.Error(BBID.Loc, "referenced value is not a basic block");
4397
4398 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4399 GV->eraseFromParent();
4400 }
4401
4402 P.ForwardRefBlockAddresses.erase(Blocks);
4403 return false;
4404}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004405
4406/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004407/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004408bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004409 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004410 return TokError("expected '{' in function body");
4411 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004412
Chris Lattner3432c622009-10-28 03:39:23 +00004413 int FunctionNumber = -1;
4414 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004415
Chris Lattner3432c622009-10-28 03:39:23 +00004416 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004417
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004418 // Resolve block addresses and allow basic blocks to be forward-declared
4419 // within this function.
4420 if (PFS.resolveForwardRefBlockAddresses())
4421 return true;
4422 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4423
Chris Lattnerbbddd962010-01-09 19:20:07 +00004424 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004425 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004426 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004427
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004428 while (Lex.getKind() != lltok::rbrace &&
4429 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004430 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004431
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004432 while (Lex.getKind() != lltok::rbrace)
4433 if (ParseUseListOrder(&PFS))
4434 return true;
4435
Chris Lattnerac161bf2009-01-02 07:01:27 +00004436 // Eat the }.
4437 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004438
Chris Lattnerac161bf2009-01-02 07:01:27 +00004439 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004440 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004441}
4442
4443/// ParseBasicBlock
4444/// ::= LabelStr? Instruction*
4445bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4446 // If this basic block starts out with a name, remember it.
4447 std::string Name;
4448 LocTy NameLoc = Lex.getLoc();
4449 if (Lex.getKind() == lltok::LabelStr) {
4450 Name = Lex.getStrVal();
4451 Lex.Lex();
4452 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004453
Chris Lattnerac161bf2009-01-02 07:01:27 +00004454 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004455 if (!BB)
4456 return Error(NameLoc,
4457 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004458
Chris Lattnerac161bf2009-01-02 07:01:27 +00004459 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004460
Chris Lattnerac161bf2009-01-02 07:01:27 +00004461 // Parse the instructions in this block until we get a terminator.
4462 Instruction *Inst;
4463 do {
4464 // This instruction may have three possibilities for a name: a) none
4465 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4466 LocTy NameLoc = Lex.getLoc();
4467 int NameID = -1;
4468 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004469
Chris Lattnerac161bf2009-01-02 07:01:27 +00004470 if (Lex.getKind() == lltok::LocalVarID) {
4471 NameID = Lex.getUIntVal();
4472 Lex.Lex();
4473 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4474 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004475 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004476 NameStr = Lex.getStrVal();
4477 Lex.Lex();
4478 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4479 return true;
4480 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004481
Chris Lattner77b89dc2009-12-30 05:23:43 +00004482 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004483 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004484 case InstError: return true;
4485 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004486 BB->getInstList().push_back(Inst);
4487
Chris Lattner77b89dc2009-12-30 05:23:43 +00004488 // With a normal result, we check to see if the instruction is followed by
4489 // a comma and metadata.
4490 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004491 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004492 return true;
4493 break;
4494 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004495 BB->getInstList().push_back(Inst);
4496
Chris Lattner77b89dc2009-12-30 05:23:43 +00004497 // If the instruction parser ate an extra comma at the end of it, it
4498 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004499 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004500 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004501 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004502 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004503
Chris Lattnerac161bf2009-01-02 07:01:27 +00004504 // Set the name on the instruction.
4505 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4506 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004507
Chris Lattnerac161bf2009-01-02 07:01:27 +00004508 return false;
4509}
4510
4511//===----------------------------------------------------------------------===//
4512// Instruction Parsing.
4513//===----------------------------------------------------------------------===//
4514
4515/// ParseInstruction - Parse one of the many different instructions.
4516///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004517int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4518 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004519 lltok::Kind Token = Lex.getKind();
4520 if (Token == lltok::Eof)
4521 return TokError("found end of file when expecting more instructions");
4522 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004523 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004524 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004525
Chris Lattnerac161bf2009-01-02 07:01:27 +00004526 switch (Token) {
4527 default: return Error(Loc, "expected instruction opcode");
4528 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004529 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004530 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4531 case lltok::kw_br: return ParseBr(Inst, PFS);
4532 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004533 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004534 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004535 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004536 // Binary Operators.
4537 case lltok::kw_add:
4538 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004539 case lltok::kw_mul:
4540 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004541 bool NUW = EatIfPresent(lltok::kw_nuw);
4542 bool NSW = EatIfPresent(lltok::kw_nsw);
4543 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004544
Chris Lattnera676c0f2011-02-07 16:40:21 +00004545 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004546
Chris Lattnera676c0f2011-02-07 16:40:21 +00004547 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4548 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4549 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004550 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004551 case lltok::kw_fadd:
4552 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004553 case lltok::kw_fmul:
4554 case lltok::kw_fdiv:
4555 case lltok::kw_frem: {
4556 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4557 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4558 if (Res != 0)
4559 return Res;
4560 if (FMF.any())
4561 Inst->setFastMathFlags(FMF);
4562 return 0;
4563 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004564
Chris Lattner35315d02011-02-06 21:44:57 +00004565 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004566 case lltok::kw_udiv:
4567 case lltok::kw_lshr:
4568 case lltok::kw_ashr: {
4569 bool Exact = EatIfPresent(lltok::kw_exact);
4570
4571 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4572 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4573 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004574 }
4575
Chris Lattnerac161bf2009-01-02 07:01:27 +00004576 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004577 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004578 case lltok::kw_and:
4579 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004580 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00004581 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4582 case lltok::kw_fcmp: {
4583 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4584 int Res = ParseCompare(Inst, PFS, KeywordVal);
4585 if (Res != 0)
4586 return Res;
4587 if (FMF.any())
4588 Inst->setFastMathFlags(FMF);
4589 return 0;
4590 }
4591
Chris Lattnerac161bf2009-01-02 07:01:27 +00004592 // Casts.
4593 case lltok::kw_trunc:
4594 case lltok::kw_zext:
4595 case lltok::kw_sext:
4596 case lltok::kw_fptrunc:
4597 case lltok::kw_fpext:
4598 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004599 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004600 case lltok::kw_uitofp:
4601 case lltok::kw_sitofp:
4602 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004603 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004604 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004605 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004606 // Other.
4607 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004608 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004609 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4610 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4611 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4612 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004613 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004614 // Call.
4615 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4616 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4617 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004618 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004619 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004620 case lltok::kw_load: return ParseLoad(Inst, PFS);
4621 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004622 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4623 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004624 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004625 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4626 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4627 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4628 }
4629}
4630
4631/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4632bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004633 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004634 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004635 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004636 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4637 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4638 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4639 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4640 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4641 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4642 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4643 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4644 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4645 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4646 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4647 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4648 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4649 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4650 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4651 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4652 }
4653 } else {
4654 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004655 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004656 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4657 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4658 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4659 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4660 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4661 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4662 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4663 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4664 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4665 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4666 }
4667 }
4668 Lex.Lex();
4669 return false;
4670}
4671
4672//===----------------------------------------------------------------------===//
4673// Terminator Instructions.
4674//===----------------------------------------------------------------------===//
4675
4676/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004677/// ::= 'ret' void (',' !dbg, !1)*
4678/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004679bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004680 PerFunctionState &PFS) {
4681 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004682 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004683 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004684
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004685 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004686
Chris Lattnerfdd87902009-10-05 05:54:46 +00004687 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004688 if (!ResType->isVoidTy())
4689 return Error(TypeLoc, "value doesn't match function result type '" +
4690 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004691
Owen Anderson55f1c092009-08-13 21:58:54 +00004692 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004693 return false;
4694 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004695
Chris Lattnerac161bf2009-01-02 07:01:27 +00004696 Value *RV;
4697 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004698
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004699 if (ResType != RV->getType())
4700 return Error(TypeLoc, "value doesn't match function result type '" +
4701 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004702
Owen Anderson55f1c092009-08-13 21:58:54 +00004703 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004704 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004705}
4706
4707
4708/// ParseBr
4709/// ::= 'br' TypeAndValue
4710/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4711bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4712 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004713 Value *Op0;
4714 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004715 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004716
Chris Lattnerac161bf2009-01-02 07:01:27 +00004717 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4718 Inst = BranchInst::Create(BB);
4719 return false;
4720 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004721
Owen Anderson55f1c092009-08-13 21:58:54 +00004722 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004723 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004724
Chris Lattnerac161bf2009-01-02 07:01:27 +00004725 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004726 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004727 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004728 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004729 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004730
Chris Lattner3ed871f2009-10-27 19:13:16 +00004731 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004732 return false;
4733}
4734
4735/// ParseSwitch
4736/// Instruction
4737/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4738/// JumpTable
4739/// ::= (TypeAndValue ',' TypeAndValue)*
4740bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4741 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004742 Value *Cond;
4743 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004744 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4745 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004746 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004747 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4748 return true;
4749
Duncan Sands19d0b472010-02-16 11:11:14 +00004750 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004751 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004752
Chris Lattnerac161bf2009-01-02 07:01:27 +00004753 // Parse the jump table pairs.
4754 SmallPtrSet<Value*, 32> SeenCases;
4755 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4756 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004757 Value *Constant;
4758 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004759
Chris Lattnerac161bf2009-01-02 07:01:27 +00004760 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4761 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004762 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004763 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004764
David Blaikie70573dc2014-11-19 07:49:26 +00004765 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004766 return Error(CondLoc, "duplicate case value in switch");
4767 if (!isa<ConstantInt>(Constant))
4768 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004769
Chris Lattner3ed871f2009-10-27 19:13:16 +00004770 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004771 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004772
Chris Lattnerac161bf2009-01-02 07:01:27 +00004773 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004774
Chris Lattner3ed871f2009-10-27 19:13:16 +00004775 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004776 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4777 SI->addCase(Table[i].first, Table[i].second);
4778 Inst = SI;
4779 return false;
4780}
4781
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004782/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00004783/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004784/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4785bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004786 LocTy AddrLoc;
4787 Value *Address;
4788 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004789 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4790 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00004791 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004792
Duncan Sands19d0b472010-02-16 11:11:14 +00004793 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004794 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004795
Chris Lattner3ed871f2009-10-27 19:13:16 +00004796 // Parse the destination list.
4797 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004798
Chris Lattner3ed871f2009-10-27 19:13:16 +00004799 if (Lex.getKind() != lltok::rsquare) {
4800 BasicBlock *DestBB;
4801 if (ParseTypeAndBasicBlock(DestBB, PFS))
4802 return true;
4803 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004804
Chris Lattner3ed871f2009-10-27 19:13:16 +00004805 while (EatIfPresent(lltok::comma)) {
4806 if (ParseTypeAndBasicBlock(DestBB, PFS))
4807 return true;
4808 DestList.push_back(DestBB);
4809 }
4810 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004811
Chris Lattner3ed871f2009-10-27 19:13:16 +00004812 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4813 return true;
4814
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004815 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00004816 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4817 IBI->addDestination(DestList[i]);
4818 Inst = IBI;
4819 return false;
4820}
4821
4822
Chris Lattnerac161bf2009-01-02 07:01:27 +00004823/// ParseInvoke
4824/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4825/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4826bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4827 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00004828 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004829 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00004830 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004831 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004832 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004833 LocTy RetTypeLoc;
4834 ValID CalleeID;
4835 SmallVector<ParamInfo, 16> ArgList;
4836
Chris Lattner3ed871f2009-10-27 19:13:16 +00004837 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004838 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004839 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004840 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004841 ParseValID(CalleeID) ||
4842 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004843 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4844 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004845 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004846 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004847 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004848 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004849 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004850
Chris Lattnerac161bf2009-01-02 07:01:27 +00004851 // If RetType is a non-function pointer type, then this is the short syntax
4852 // for the call, which means that RetType is just the return type. Infer the
4853 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00004854 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4855 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004856 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004857 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004858 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4859 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004860
Chris Lattnerac161bf2009-01-02 07:01:27 +00004861 if (!FunctionType::isValidReturnType(RetType))
4862 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004863
Owen Anderson4056ca92009-07-29 22:17:13 +00004864 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004865 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004866
Chris Lattnerac161bf2009-01-02 07:01:27 +00004867 // Look up the callee.
4868 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00004869 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4870 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004871
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004872 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004873 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004874 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004875 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4876 AttributeSet::ReturnIndex,
4877 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004878
Chris Lattnerac161bf2009-01-02 07:01:27 +00004879 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004880
Chris Lattnerac161bf2009-01-02 07:01:27 +00004881 // Loop through FunctionType's arguments and ensure they are specified
4882 // correctly. Also, gather any parameter attributes.
4883 FunctionType::param_iterator I = Ty->param_begin();
4884 FunctionType::param_iterator E = Ty->param_end();
4885 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004886 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004887 if (I != E) {
4888 ExpectedTy = *I++;
4889 } else if (!Ty->isVarArg()) {
4890 return Error(ArgList[i].Loc, "too many arguments specified");
4891 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004892
Chris Lattnerac161bf2009-01-02 07:01:27 +00004893 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4894 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004895 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004896 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004897 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4898 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004899 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4900 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004901 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004902
Chris Lattnerac161bf2009-01-02 07:01:27 +00004903 if (I != E)
4904 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004905
David Majnemer8d22abd2015-02-23 00:01:32 +00004906 if (FnAttrs.hasAttributes()) {
4907 if (FnAttrs.hasAlignmentAttr())
4908 return Error(CallLoc, "invoke instructions may not have an alignment");
4909
Bill Wendlingf5075a42013-01-27 02:24:02 +00004910 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4911 AttributeSet::FunctionIndex,
4912 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00004913 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004914
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004915 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004916 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004917
David Blaikie3e807092015-05-13 18:35:26 +00004918 InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004919 II->setCallingConv(CC);
4920 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004921 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004922 Inst = II;
4923 return false;
4924}
4925
Bill Wendlingf891bf82011-07-31 06:30:59 +00004926/// ParseResume
4927/// ::= 'resume' TypeAndValue
4928bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4929 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004930 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4931 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004932
Bill Wendlingf891bf82011-07-31 06:30:59 +00004933 ResumeInst *RI = ResumeInst::Create(Exn);
4934 Inst = RI;
4935 return false;
4936}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004937
4938//===----------------------------------------------------------------------===//
4939// Binary Operators.
4940//===----------------------------------------------------------------------===//
4941
4942/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004943/// ::= ArithmeticOps TypeAndValue ',' Value
4944///
4945/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4946/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00004947bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004948 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004949 LocTy Loc; Value *LHS, *RHS;
4950 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4951 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4952 ParseValue(LHS->getType(), RHS, PFS))
4953 return true;
4954
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004955 bool Valid;
4956 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00004957 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004958 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00004959 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4960 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004961 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00004962 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4963 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004964 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004965
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004966 if (!Valid)
4967 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004968
Chris Lattnerac161bf2009-01-02 07:01:27 +00004969 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4970 return false;
4971}
4972
4973/// ParseLogical
4974/// ::= ArithmeticOps TypeAndValue ',' Value {
4975bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4976 unsigned Opc) {
4977 LocTy Loc; Value *LHS, *RHS;
4978 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4979 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4980 ParseValue(LHS->getType(), RHS, PFS))
4981 return true;
4982
Duncan Sands9dff9be2010-02-15 16:12:20 +00004983 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004984 return Error(Loc,"instruction requires integer or integer vector operands");
4985
4986 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4987 return false;
4988}
4989
4990
4991/// ParseCompare
4992/// ::= 'icmp' IPredicates TypeAndValue ',' Value
4993/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004994bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4995 unsigned Opc) {
4996 // Parse the integer/fp comparison predicate.
4997 LocTy Loc;
4998 unsigned Pred;
4999 Value *LHS, *RHS;
5000 if (ParseCmpPredicate(Pred, Opc) ||
5001 ParseTypeAndValue(LHS, Loc, PFS) ||
5002 ParseToken(lltok::comma, "expected ',' after compare value") ||
5003 ParseValue(LHS->getType(), RHS, PFS))
5004 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005005
Chris Lattnerac161bf2009-01-02 07:01:27 +00005006 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005007 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005008 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005009 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005010 } else {
5011 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005012 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005013 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005014 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005015 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005016 }
5017 return false;
5018}
5019
5020//===----------------------------------------------------------------------===//
5021// Other Instructions.
5022//===----------------------------------------------------------------------===//
5023
5024
5025/// ParseCast
5026/// ::= CastOpc TypeAndValue 'to' Type
5027bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5028 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005029 LocTy Loc;
5030 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005031 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005032 if (ParseTypeAndValue(Op, Loc, PFS) ||
5033 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5034 ParseType(DestTy))
5035 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005036
Chris Lattner89d856e2009-03-01 00:53:13 +00005037 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5038 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005039 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005040 getTypeString(Op->getType()) + "' to '" +
5041 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005042 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005043 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5044 return false;
5045}
5046
5047/// ParseSelect
5048/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5049bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5050 LocTy Loc;
5051 Value *Op0, *Op1, *Op2;
5052 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5053 ParseToken(lltok::comma, "expected ',' after select condition") ||
5054 ParseTypeAndValue(Op1, PFS) ||
5055 ParseToken(lltok::comma, "expected ',' after select value") ||
5056 ParseTypeAndValue(Op2, PFS))
5057 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005058
Chris Lattnerac161bf2009-01-02 07:01:27 +00005059 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5060 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005061
Chris Lattnerac161bf2009-01-02 07:01:27 +00005062 Inst = SelectInst::Create(Op0, Op1, Op2);
5063 return false;
5064}
5065
Chris Lattnerb55ab542009-01-05 08:18:44 +00005066/// ParseVA_Arg
5067/// ::= 'va_arg' TypeAndValue ',' Type
5068bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005069 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005070 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005071 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005072 if (ParseTypeAndValue(Op, PFS) ||
5073 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005074 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005075 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005076
Chris Lattnerb55ab542009-01-05 08:18:44 +00005077 if (!EltTy->isFirstClassType())
5078 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005079
5080 Inst = new VAArgInst(Op, EltTy);
5081 return false;
5082}
5083
5084/// ParseExtractElement
5085/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5086bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5087 LocTy Loc;
5088 Value *Op0, *Op1;
5089 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5090 ParseToken(lltok::comma, "expected ',' after extract value") ||
5091 ParseTypeAndValue(Op1, PFS))
5092 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005093
Chris Lattnerac161bf2009-01-02 07:01:27 +00005094 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5095 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005096
Eric Christopherc9742252009-07-25 02:28:41 +00005097 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005098 return false;
5099}
5100
5101/// ParseInsertElement
5102/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5103bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5104 LocTy Loc;
5105 Value *Op0, *Op1, *Op2;
5106 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5107 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5108 ParseTypeAndValue(Op1, PFS) ||
5109 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5110 ParseTypeAndValue(Op2, PFS))
5111 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005112
Chris Lattnerac161bf2009-01-02 07:01:27 +00005113 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005114 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005115
Chris Lattnerac161bf2009-01-02 07:01:27 +00005116 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5117 return false;
5118}
5119
5120/// ParseShuffleVector
5121/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5122bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5123 LocTy Loc;
5124 Value *Op0, *Op1, *Op2;
5125 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5126 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5127 ParseTypeAndValue(Op1, PFS) ||
5128 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5129 ParseTypeAndValue(Op2, PFS))
5130 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005131
Chris Lattnerac161bf2009-01-02 07:01:27 +00005132 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005133 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005134
Chris Lattnerac161bf2009-01-02 07:01:27 +00005135 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5136 return false;
5137}
5138
5139/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005140/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005141int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005142 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005143 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005144
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005145 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005146 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5147 ParseValue(Ty, Op0, PFS) ||
5148 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005149 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005150 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5151 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005152
Chris Lattnerf4f03422009-12-30 05:27:33 +00005153 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005154 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5155 while (1) {
5156 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005157
Chris Lattner3822f632009-01-02 08:05:26 +00005158 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005159 break;
5160
Chris Lattnerf4f03422009-12-30 05:27:33 +00005161 if (Lex.getKind() == lltok::MetadataVar) {
5162 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005163 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005164 }
Devang Patel8f842d32009-10-16 18:45:49 +00005165
Chris Lattner3822f632009-01-02 08:05:26 +00005166 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005167 ParseValue(Ty, Op0, PFS) ||
5168 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005169 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005170 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5171 return true;
5172 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005173
Chris Lattnerac161bf2009-01-02 07:01:27 +00005174 if (!Ty->isFirstClassType())
5175 return Error(TypeLoc, "phi node must have first class type");
5176
Jay Foad52131342011-03-30 11:28:46 +00005177 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005178 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5179 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5180 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005181 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005182}
5183
Bill Wendlingfae14752011-08-12 20:24:12 +00005184/// ParseLandingPad
5185/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5186/// Clause
5187/// ::= 'catch' TypeAndValue
5188/// ::= 'filter'
5189/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5190bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005191 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005192
David Majnemer7fddecc2015-06-17 20:52:32 +00005193 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005194 return true;
5195
David Majnemer7fddecc2015-06-17 20:52:32 +00005196 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005197 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5198
5199 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5200 LandingPadInst::ClauseType CT;
5201 if (EatIfPresent(lltok::kw_catch))
5202 CT = LandingPadInst::Catch;
5203 else if (EatIfPresent(lltok::kw_filter))
5204 CT = LandingPadInst::Filter;
5205 else
5206 return TokError("expected 'catch' or 'filter' clause type");
5207
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005208 Value *V;
5209 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005210 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005211 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005212
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005213 // A 'catch' type expects a non-array constant. A filter clause expects an
5214 // array constant.
5215 if (CT == LandingPadInst::Catch) {
5216 if (isa<ArrayType>(V->getType()))
5217 Error(VLoc, "'catch' clause has an invalid type");
5218 } else {
5219 if (!isa<ArrayType>(V->getType()))
5220 Error(VLoc, "'filter' clause has an invalid type");
5221 }
5222
Owen Andersonf8f259d2015-03-09 07:13:42 +00005223 Constant *CV = dyn_cast<Constant>(V);
5224 if (!CV)
5225 return Error(VLoc, "clause argument must be a constant");
5226 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005227 }
5228
Owen Andersonf8f259d2015-03-09 07:13:42 +00005229 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005230 return false;
5231}
5232
Chris Lattnerac161bf2009-01-02 07:01:27 +00005233/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00005234/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5235/// ParameterList OptionalAttrs
5236/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5237/// ParameterList OptionalAttrs
5238/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005239/// ParameterList OptionalAttrs
5240bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005241 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005242 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005243 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005244 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005245 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005246 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005247 LocTy RetTypeLoc;
5248 ValID CalleeID;
5249 SmallVector<ParamInfo, 16> ArgList;
5250 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005251
Reid Kleckner5772b772014-04-24 20:14:34 +00005252 if ((TCK != CallInst::TCK_None &&
5253 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005254 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00005255 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005256 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005257 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005258 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5259 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005260 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005261 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005262 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005263
Chris Lattnerac161bf2009-01-02 07:01:27 +00005264 // If RetType is a non-function pointer type, then this is the short syntax
5265 // for the call, which means that RetType is just the return type. Infer the
5266 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005267 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5268 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005269 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005270 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005271 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5272 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005273
Chris Lattnerac161bf2009-01-02 07:01:27 +00005274 if (!FunctionType::isValidReturnType(RetType))
5275 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005276
Owen Anderson4056ca92009-07-29 22:17:13 +00005277 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005278 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005279
Chris Lattnerac161bf2009-01-02 07:01:27 +00005280 // Look up the callee.
5281 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005282 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5283 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005284
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005285 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005286 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005287 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005288 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5289 AttributeSet::ReturnIndex,
5290 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005291
Chris Lattnerac161bf2009-01-02 07:01:27 +00005292 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005293
Chris Lattnerac161bf2009-01-02 07:01:27 +00005294 // Loop through FunctionType's arguments and ensure they are specified
5295 // correctly. Also, gather any parameter attributes.
5296 FunctionType::param_iterator I = Ty->param_begin();
5297 FunctionType::param_iterator E = Ty->param_end();
5298 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005299 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005300 if (I != E) {
5301 ExpectedTy = *I++;
5302 } else if (!Ty->isVarArg()) {
5303 return Error(ArgList[i].Loc, "too many arguments specified");
5304 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005305
Chris Lattnerac161bf2009-01-02 07:01:27 +00005306 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5307 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005308 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005309 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005310 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5311 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005312 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5313 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005314 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005315
Chris Lattnerac161bf2009-01-02 07:01:27 +00005316 if (I != E)
5317 return Error(CallLoc, "not enough parameters specified for call");
5318
David Majnemer8d22abd2015-02-23 00:01:32 +00005319 if (FnAttrs.hasAttributes()) {
5320 if (FnAttrs.hasAlignmentAttr())
5321 return Error(CallLoc, "call instructions may not have an alignment");
5322
Bill Wendlingf5075a42013-01-27 02:24:02 +00005323 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5324 AttributeSet::FunctionIndex,
5325 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005326 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005327
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005328 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005329 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005330
David Blaikie348de692015-04-23 21:36:23 +00005331 CallInst *CI = CallInst::Create(Ty, Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00005332 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005333 CI->setCallingConv(CC);
5334 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005335 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005336 Inst = CI;
5337 return false;
5338}
5339
5340//===----------------------------------------------------------------------===//
5341// Memory Instructions.
5342//===----------------------------------------------------------------------===//
5343
5344/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00005345/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005346int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005347 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005348 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005349 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005350 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005351
5352 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5353
David Majnemera3b0eb22015-02-16 08:38:03 +00005354 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005355
David Majnemera3b0eb22015-02-16 08:38:03 +00005356 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5357 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005358
Chris Lattnerb2f39502009-12-30 05:44:30 +00005359 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005360 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005361 if (Lex.getKind() == lltok::kw_align) {
5362 if (ParseOptionalAlignment(Alignment)) return true;
5363 } else if (Lex.getKind() == lltok::MetadataVar) {
5364 AteExtraComma = true;
5365 } else {
5366 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5367 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5368 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005369 }
5370 }
5371
Dan Gohman2140a742010-05-28 01:14:11 +00005372 if (Size && !Size->getType()->isIntegerTy())
5373 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005374
Reid Kleckner436c42e2014-01-17 23:58:17 +00005375 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5376 AI->setUsedWithInAlloca(IsInAlloca);
5377 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005378 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005379}
5380
5381/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005382/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005383/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005384/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005385int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005386 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005387 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005388 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005389 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005390 AtomicOrdering Ordering = NotAtomic;
5391 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005392
5393 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005394 isAtomic = true;
5395 Lex.Lex();
5396 }
5397
Chris Lattnerbc639292011-11-27 06:56:53 +00005398 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005399 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005400 isVolatile = true;
5401 Lex.Lex();
5402 }
5403
David Blaikie15d9a4c2015-04-06 20:59:48 +00005404 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005405 LocTy ExplicitTypeLoc = Lex.getLoc();
5406 if (ParseType(Ty) ||
5407 ParseToken(lltok::comma, "expected comma after load's type") ||
5408 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005409 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005410 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5411 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005412
David Blaikie15d9a4c2015-04-06 20:59:48 +00005413 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005414 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005415 if (isAtomic && !Alignment)
5416 return Error(Loc, "atomic load must have explicit non-zero alignment");
5417 if (Ordering == Release || Ordering == AcquireRelease)
5418 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005419
David Blaikiea79ac142015-02-27 21:17:42 +00005420 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5421 return Error(ExplicitTypeLoc,
5422 "explicit pointee type doesn't match operand's pointee type");
5423
David Blaikie15d9a4c2015-04-06 20:59:48 +00005424 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005425 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005426}
5427
5428/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005429
5430/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5431/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005432/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005433int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005434 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005435 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005436 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005437 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005438 AtomicOrdering Ordering = NotAtomic;
5439 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005440
5441 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005442 isAtomic = true;
5443 Lex.Lex();
5444 }
5445
Chris Lattnerbc639292011-11-27 06:56:53 +00005446 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005447 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005448 isVolatile = true;
5449 Lex.Lex();
5450 }
5451
Chris Lattnerac161bf2009-01-02 07:01:27 +00005452 if (ParseTypeAndValue(Val, Loc, PFS) ||
5453 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005454 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005455 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005456 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005457 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005458
Duncan Sands19d0b472010-02-16 11:11:14 +00005459 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005460 return Error(PtrLoc, "store operand must be a pointer");
5461 if (!Val->getType()->isFirstClassType())
5462 return Error(Loc, "store operand must be a first class value");
5463 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5464 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005465 if (isAtomic && !Alignment)
5466 return Error(Loc, "atomic store must have explicit non-zero alignment");
5467 if (Ordering == Acquire || Ordering == AcquireRelease)
5468 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005469
Eli Friedman59b66882011-08-09 23:02:53 +00005470 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005471 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005472}
5473
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005474/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005475/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5476/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005477int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005478 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5479 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005480 AtomicOrdering SuccessOrdering = NotAtomic;
5481 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005482 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005483 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005484 bool isWeak = false;
5485
5486 if (EatIfPresent(lltok::kw_weak))
5487 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005488
5489 if (EatIfPresent(lltok::kw_volatile))
5490 isVolatile = true;
5491
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005492 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5493 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5494 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5495 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5496 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005497 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5498 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005499 return true;
5500
Tim Northovere94a5182014-03-11 10:48:52 +00005501 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005502 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005503 if (SuccessOrdering < FailureOrdering)
5504 return TokError("cmpxchg must be at least as ordered on success as failure");
5505 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5506 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005507 if (!Ptr->getType()->isPointerTy())
5508 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5509 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5510 return Error(CmpLoc, "compare value and pointer type do not match");
5511 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5512 return Error(NewLoc, "new value and pointer type do not match");
5513 if (!New->getType()->isIntegerTy())
5514 return Error(NewLoc, "cmpxchg operand must be an integer");
5515 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5516 if (Size < 8 || (Size & (Size - 1)))
5517 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5518 " integer");
5519
Tim Northover420a2162014-06-13 14:24:07 +00005520 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5521 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005522 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00005523 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005524 Inst = CXI;
5525 return AteExtraComma ? InstExtraComma : InstNormal;
5526}
5527
5528/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00005529/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5530/// 'singlethread'? AtomicOrdering
5531int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005532 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5533 bool AteExtraComma = false;
5534 AtomicOrdering Ordering = NotAtomic;
5535 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005536 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005537 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00005538
5539 if (EatIfPresent(lltok::kw_volatile))
5540 isVolatile = true;
5541
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005542 switch (Lex.getKind()) {
5543 default: return TokError("expected binary operation in atomicrmw");
5544 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5545 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5546 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5547 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5548 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5549 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5550 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5551 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5552 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5553 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5554 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5555 }
5556 Lex.Lex(); // Eat the operation.
5557
5558 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5559 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5560 ParseTypeAndValue(Val, ValLoc, PFS) ||
5561 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5562 return true;
5563
5564 if (Ordering == Unordered)
5565 return TokError("atomicrmw cannot be unordered");
5566 if (!Ptr->getType()->isPointerTy())
5567 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5568 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5569 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5570 if (!Val->getType()->isIntegerTy())
5571 return Error(ValLoc, "atomicrmw operand must be an integer");
5572 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5573 if (Size < 8 || (Size & (Size - 1)))
5574 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5575 " integer");
5576
5577 AtomicRMWInst *RMWI =
5578 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5579 RMWI->setVolatile(isVolatile);
5580 Inst = RMWI;
5581 return AteExtraComma ? InstExtraComma : InstNormal;
5582}
5583
Eli Friedmanfee02c62011-07-25 23:16:38 +00005584/// ParseFence
5585/// ::= 'fence' 'singlethread'? AtomicOrdering
5586int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5587 AtomicOrdering Ordering = NotAtomic;
5588 SynchronizationScope Scope = CrossThread;
5589 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5590 return true;
5591
5592 if (Ordering == Unordered)
5593 return TokError("fence cannot be unordered");
5594 if (Ordering == Monotonic)
5595 return TokError("fence cannot be monotonic");
5596
5597 Inst = new FenceInst(Context, Ordering, Scope);
5598 return InstNormal;
5599}
5600
Chris Lattnerac161bf2009-01-02 07:01:27 +00005601/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00005602/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005603int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005604 Value *Ptr = nullptr;
5605 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005606 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00005607
Dan Gohman16cbbe42009-07-29 15:58:36 +00005608 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00005609
David Blaikie79e6c742015-02-27 19:29:02 +00005610 Type *Ty = nullptr;
5611 LocTy ExplicitTypeLoc = Lex.getLoc();
5612 if (ParseType(Ty) ||
5613 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5614 ParseTypeAndValue(Ptr, Loc, PFS))
5615 return true;
5616
Eli Benderskyd9806682013-04-22 17:03:42 +00005617 Type *BaseType = Ptr->getType();
5618 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5619 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005620 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005621
David Blaikie8d757942015-03-09 23:08:44 +00005622 if (Ty != BasePointerType->getElementType())
5623 return Error(ExplicitTypeLoc,
5624 "explicit pointee type doesn't match operand's pointee type");
5625
Chris Lattnerac161bf2009-01-02 07:01:27 +00005626 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005627 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005628 // GEP returns a vector of pointers if at least one of parameters is a vector.
5629 // All vector parameters should have the same vector width.
5630 unsigned GEPWidth = BaseType->isVectorTy() ?
5631 BaseType->getVectorNumElements() : 0;
5632
Chris Lattner3822f632009-01-02 08:05:26 +00005633 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00005634 if (Lex.getKind() == lltok::MetadataVar) {
5635 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00005636 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005637 }
Chris Lattner3822f632009-01-02 08:05:26 +00005638 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005639 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005640 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005641
Nadav Rotem3924cb02011-12-05 06:29:09 +00005642 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005643 unsigned ValNumEl = Val->getType()->getVectorNumElements();
5644 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00005645 return Error(EltLoc,
5646 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005647 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005648 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005649 Indices.push_back(Val);
5650 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005651
Owen Andersone90f9922015-03-10 06:34:57 +00005652 SmallPtrSet<const Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00005653 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00005654 return Error(Loc, "base element of getelementptr must be sized");
5655
David Blaikied33bad32015-04-17 22:32:13 +00005656 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005657 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00005658 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00005659 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00005660 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005661 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005662}
5663
5664/// ParseExtractValue
5665/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005666int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005667 Value *Val; LocTy Loc;
5668 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005669 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005670 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005671 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005672 return true;
5673
Chris Lattner392be582010-02-12 20:49:41 +00005674 if (!Val->getType()->isAggregateType())
5675 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005676
Jay Foad57aa6362011-07-13 10:26:04 +00005677 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005678 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00005679 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005680 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005681}
5682
5683/// ParseInsertValue
5684/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005685int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005686 Value *Val0, *Val1; LocTy Loc0, Loc1;
5687 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005688 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005689 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5690 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5691 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005692 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005693 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005694
Chris Lattner392be582010-02-12 20:49:41 +00005695 if (!Val0->getType()->isAggregateType())
5696 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005697
David Majnemer30074532015-02-11 07:43:58 +00005698 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5699 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005700 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00005701 if (IndexedType != Val1->getType())
5702 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5703 getTypeString(Val1->getType()) + "' instead of '" +
5704 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00005705 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005706 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005707}
Nick Lewycky49f89192009-04-04 07:22:01 +00005708
5709//===----------------------------------------------------------------------===//
5710// Embedded metadata.
5711//===----------------------------------------------------------------------===//
5712
5713/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005714/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005715/// Element
5716/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005717bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00005718 if (ParseToken(lltok::lbrace, "expected '{' here"))
5719 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005720
Dan Gohman1e0213a2010-07-13 19:33:27 +00005721 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005722 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00005723 return false;
5724
Nick Lewycky49f89192009-04-04 07:22:01 +00005725 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005726 // Null is a special case since it is typeless.
5727 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005728 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005729 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005730 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005731
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005732 Metadata *MD;
5733 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005734 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005735 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00005736 } while (EatIfPresent(lltok::comma));
5737
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005738 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00005739}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005740
5741//===----------------------------------------------------------------------===//
5742// Use-list order directives.
5743//===----------------------------------------------------------------------===//
5744bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5745 SMLoc Loc) {
5746 if (V->use_empty())
5747 return Error(Loc, "value has no uses");
5748
5749 unsigned NumUses = 0;
5750 SmallDenseMap<const Use *, unsigned, 16> Order;
5751 for (const Use &U : V->uses()) {
5752 if (++NumUses > Indexes.size())
5753 break;
5754 Order[&U] = Indexes[NumUses - 1];
5755 }
5756 if (NumUses < 2)
5757 return Error(Loc, "value only has one use");
5758 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5759 return Error(Loc, "wrong number of indexes, expected " +
5760 Twine(std::distance(V->use_begin(), V->use_end())));
5761
5762 V->sortUseList([&](const Use &L, const Use &R) {
5763 return Order.lookup(&L) < Order.lookup(&R);
5764 });
5765 return false;
5766}
5767
5768/// ParseUseListOrderIndexes
5769/// ::= '{' uint32 (',' uint32)+ '}'
5770bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5771 SMLoc Loc = Lex.getLoc();
5772 if (ParseToken(lltok::lbrace, "expected '{' here"))
5773 return true;
5774 if (Lex.getKind() == lltok::rbrace)
5775 return Lex.Error("expected non-empty list of uselistorder indexes");
5776
5777 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5778 // indexes should be distinct numbers in the range [0, size-1], and should
5779 // not be in order.
5780 unsigned Offset = 0;
5781 unsigned Max = 0;
5782 bool IsOrdered = true;
5783 assert(Indexes.empty() && "Expected empty order vector");
5784 do {
5785 unsigned Index;
5786 if (ParseUInt32(Index))
5787 return true;
5788
5789 // Update consistency checks.
5790 Offset += Index - Indexes.size();
5791 Max = std::max(Max, Index);
5792 IsOrdered &= Index == Indexes.size();
5793
5794 Indexes.push_back(Index);
5795 } while (EatIfPresent(lltok::comma));
5796
5797 if (ParseToken(lltok::rbrace, "expected '}' here"))
5798 return true;
5799
5800 if (Indexes.size() < 2)
5801 return Error(Loc, "expected >= 2 uselistorder indexes");
5802 if (Offset != 0 || Max >= Indexes.size())
5803 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5804 if (IsOrdered)
5805 return Error(Loc, "expected uselistorder indexes to change the order");
5806
5807 return false;
5808}
5809
5810/// ParseUseListOrder
5811/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5812bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5813 SMLoc Loc = Lex.getLoc();
5814 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5815 return true;
5816
5817 Value *V;
5818 SmallVector<unsigned, 16> Indexes;
5819 if (ParseTypeAndValue(V, PFS) ||
5820 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5821 ParseUseListOrderIndexes(Indexes))
5822 return true;
5823
5824 return sortUseListOrder(V, Indexes, Loc);
5825}
5826
5827/// ParseUseListOrderBB
5828/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5829bool LLParser::ParseUseListOrderBB() {
5830 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5831 SMLoc Loc = Lex.getLoc();
5832 Lex.Lex();
5833
5834 ValID Fn, Label;
5835 SmallVector<unsigned, 16> Indexes;
5836 if (ParseValID(Fn) ||
5837 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5838 ParseValID(Label) ||
5839 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5840 ParseUseListOrderIndexes(Indexes))
5841 return true;
5842
5843 // Check the function.
5844 GlobalValue *GV;
5845 if (Fn.Kind == ValID::t_GlobalName)
5846 GV = M->getNamedValue(Fn.StrVal);
5847 else if (Fn.Kind == ValID::t_GlobalID)
5848 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5849 else
5850 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5851 if (!GV)
5852 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5853 auto *F = dyn_cast<Function>(GV);
5854 if (!F)
5855 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5856 if (F->isDeclaration())
5857 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5858
5859 // Check the basic block.
5860 if (Label.Kind == ValID::t_LocalID)
5861 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5862 if (Label.Kind != ValID::t_LocalName)
5863 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5864 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5865 if (!V)
5866 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5867 if (!isa<BasicBlock>(V))
5868 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5869
5870 return sortUseListOrder(V, Indexes, Loc);
5871}