blob: 0b3f76aa68cb8a4dc9d502726928ac3bf374e355 [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
51/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
52/// module.
53bool LLParser::ValidateEndOfModule() {
Manman Ren209b17c2013-09-28 00:22:27 +000054 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
55 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
56
Bill Wendlingb32b0412013-02-08 06:32:06 +000057 // Handle any function attribute group forward references.
58 for (std::map<Value*, std::vector<unsigned> >::iterator
59 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
60 I != E; ++I) {
61 Value *V = I->first;
62 std::vector<unsigned> &Vec = I->second;
63 AttrBuilder B;
64
65 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
66 VI != VE; ++VI)
67 B.merge(NumberedAttrBuilders[*VI]);
68
69 if (Function *Fn = dyn_cast<Function>(V)) {
70 AttributeSet AS = Fn->getAttributes();
71 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
72 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
73 AS.getFnAttributes());
74
75 FnAttrs.merge(B);
76
77 // If the alignment was parsed as an attribute, move to the alignment
78 // field.
79 if (FnAttrs.hasAlignmentAttr()) {
80 Fn->setAlignment(FnAttrs.getAlignment());
81 FnAttrs.removeAttribute(Attribute::Alignment);
82 }
83
84 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
85 AttributeSet::get(Context,
86 AttributeSet::FunctionIndex,
87 FnAttrs));
88 Fn->setAttributes(AS);
89 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
90 AttributeSet AS = CI->getAttributes();
91 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
92 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
93 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +000094 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +000095 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
96 AttributeSet::get(Context,
97 AttributeSet::FunctionIndex,
98 FnAttrs));
99 CI->setAttributes(AS);
100 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
101 AttributeSet AS = II->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 II->setAttributes(AS);
111 } else {
112 llvm_unreachable("invalid object with forward attribute group reference");
113 }
114 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000115
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000116 // If there are entries in ForwardRefBlockAddresses at this point, the
117 // function was never defined.
118 if (!ForwardRefBlockAddresses.empty())
119 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
120 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000121
David Majnemer19b51052015-02-11 07:43:56 +0000122 for (const auto &NT : NumberedTypes)
123 if (NT.second.second.isValid())
124 return Error(NT.second.second,
125 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000126
127 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
128 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
129 if (I->second.second.isValid())
130 return Error(I->second.second,
131 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000132
David Majnemerdad0a642014-06-27 18:19:56 +0000133 if (!ForwardRefComdats.empty())
134 return Error(ForwardRefComdats.begin()->second,
135 "use of undefined comdat '$" +
136 ForwardRefComdats.begin()->first + "'");
137
Chris Lattnerac161bf2009-01-02 07:01:27 +0000138 if (!ForwardRefVals.empty())
139 return Error(ForwardRefVals.begin()->second.second,
140 "use of undefined value '@" + ForwardRefVals.begin()->first +
141 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000142
Chris Lattnerac161bf2009-01-02 07:01:27 +0000143 if (!ForwardRefValIDs.empty())
144 return Error(ForwardRefValIDs.begin()->second.second,
145 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000146 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000147
Devang Pateld2541152009-07-08 19:23:54 +0000148 if (!ForwardRefMDNodes.empty())
149 return Error(ForwardRefMDNodes.begin()->second.second,
150 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000151 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000152
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000153 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000154 for (auto &N : NumberedMetadata) {
155 if (N.second && !N.second->isResolved())
156 N.second->resolveCycles();
157 }
Devang Pateld2541152009-07-08 19:23:54 +0000158
Chris Lattnerac161bf2009-01-02 07:01:27 +0000159 // Look for intrinsic functions and CallInst that need to be upgraded
160 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
161 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000162
Manman Ren8b4306c2013-12-02 21:29:56 +0000163 UpgradeDebugInfo(*M);
164
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000165 if (!Slots)
166 return false;
167 // Initialize the slot mapping.
168 // Because by this point we've parsed and validated everything, we can "steal"
169 // the mapping from LLParser as it doesn't need it anymore.
170 Slots->GlobalValues = std::move(NumberedVals);
171 Slots->MetadataNodes = std::move(NumberedMetadata);
172
Chris Lattnerac161bf2009-01-02 07:01:27 +0000173 return false;
174}
175
176//===----------------------------------------------------------------------===//
177// Top-Level Entities
178//===----------------------------------------------------------------------===//
179
180bool LLParser::ParseTopLevelEntities() {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000181 while (1) {
182 switch (Lex.getKind()) {
183 default: return TokError("expected top-level entity");
184 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000185 case lltok::kw_declare: if (ParseDeclare()) return true; break;
186 case lltok::kw_define: if (ParseDefine()) return true; break;
187 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
188 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000189 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000190 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000191 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000192 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000193 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000194 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000195 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000196 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000197
198 // The Global variable production with no name can have many different
199 // optional leading prefixes, the production is:
Nico Rieck7157bb72014-01-14 15:22:47 +0000200 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000201 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
Rafael Espindola45e6c192011-01-08 16:42:36 +0000202 // ('constant'|'global') ...
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000203 case lltok::kw_private: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000204 case lltok::kw_internal: // OptionalLinkage
205 case lltok::kw_weak: // OptionalLinkage
206 case lltok::kw_weak_odr: // OptionalLinkage
207 case lltok::kw_linkonce: // OptionalLinkage
208 case lltok::kw_linkonce_odr: // OptionalLinkage
209 case lltok::kw_appending: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000210 case lltok::kw_common: // OptionalLinkage
Bill Wendling03bcd6e2010-07-01 21:55:59 +0000211 case lltok::kw_extern_weak: // OptionalLinkage
Rafael Espindola52b74422014-06-03 20:00:20 +0000212 case lltok::kw_external: // OptionalLinkage
213 case lltok::kw_default: // OptionalVisibility
214 case lltok::kw_hidden: // OptionalVisibility
215 case lltok::kw_protected: // OptionalVisibility
Rafael Espindola63e92fb2014-06-03 20:07:32 +0000216 case lltok::kw_dllimport: // OptionalDLLStorageClass
217 case lltok::kw_dllexport: // OptionalDLLStorageClass
Rafael Espindola52b74422014-06-03 20:00:20 +0000218 case lltok::kw_thread_local: // OptionalThreadLocal
219 case lltok::kw_addrspace: // OptionalAddrSpace
220 case lltok::kw_constant: // GlobalType
221 case lltok::kw_global: { // GlobalType
Nico Rieck7157bb72014-01-14 15:22:47 +0000222 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000223 bool UnnamedAddr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000224 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola52b74422014-06-03 20:00:20 +0000225 bool HasLinkage;
226 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000227 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000228 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000229 ParseOptionalThreadLocal(TLM) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000230 parseOptionalUnnamedAddr(UnnamedAddr) ||
Rafael Espindola52b74422014-06-03 20:00:20 +0000231 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000232 DLLStorageClass, TLM, UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000233 return true;
234 break;
235 }
Bill Wendlinga7c38772013-02-09 15:48:49 +0000236
237 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000238 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
239 case lltok::kw_uselistorder_bb:
240 if (ParseUseListOrderBB()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000241 }
242 }
243}
244
245
246/// toplevelentity
247/// ::= 'module' 'asm' STRINGCONSTANT
248bool LLParser::ParseModuleAsm() {
249 assert(Lex.getKind() == lltok::kw_module);
250 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000251
252 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000253 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
254 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000255
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000256 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000257 return false;
258}
259
260/// toplevelentity
261/// ::= 'target' 'triple' '=' STRINGCONSTANT
262/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
263bool LLParser::ParseTargetDefinition() {
264 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000265 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000266 switch (Lex.Lex()) {
267 default: return TokError("unknown target property");
268 case lltok::kw_triple:
269 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000270 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
271 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000272 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000273 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000274 return false;
275 case lltok::kw_datalayout:
276 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000277 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
278 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000279 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000280 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000281 return false;
282 }
283}
284
Bill Wendling706d3d62012-11-28 08:41:48 +0000285/// toplevelentity
286/// ::= 'deplibs' '=' '[' ']'
287/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
288/// FIXME: Remove in 4.0. Currently parse, but ignore.
289bool LLParser::ParseDepLibs() {
290 assert(Lex.getKind() == lltok::kw_deplibs);
291 Lex.Lex();
292 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
293 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
294 return true;
295
296 if (EatIfPresent(lltok::rsquare))
297 return false;
298
299 do {
300 std::string Str;
301 if (ParseStringConstant(Str)) return true;
302 } while (EatIfPresent(lltok::comma));
303
304 return ParseToken(lltok::rsquare, "expected ']' at end of list");
305}
306
Dan Gohman466876b2009-08-12 23:32:33 +0000307/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000308/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000309bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000310 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000311 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000312 Lex.Lex(); // eat LocalVarID;
313
314 if (ParseToken(lltok::equal, "expected '=' after name") ||
315 ParseToken(lltok::kw_type, "expected 'type' after '='"))
316 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000317
Craig Topper2617dcc2014-04-15 06:32:26 +0000318 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000319 if (ParseStructDefinition(TypeLoc, "",
320 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000321
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000322 if (!isa<StructType>(Result)) {
323 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
324 if (Entry.first)
325 return Error(TypeLoc, "non-struct types may not be recursive");
326 Entry.first = Result;
327 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000328 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000329
Chris Lattnerac161bf2009-01-02 07:01:27 +0000330 return false;
331}
332
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000333
Chris Lattnerac161bf2009-01-02 07:01:27 +0000334/// toplevelentity
335/// ::= LocalVar '=' 'type' type
336bool LLParser::ParseNamedType() {
337 std::string Name = Lex.getStrVal();
338 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000339 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000340
Chris Lattner3822f632009-01-02 08:05:26 +0000341 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000342 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000343 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000344
Craig Topper2617dcc2014-04-15 06:32:26 +0000345 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000346 if (ParseStructDefinition(NameLoc, Name,
347 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000348
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000349 if (!isa<StructType>(Result)) {
350 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
351 if (Entry.first)
352 return Error(NameLoc, "non-struct types may not be recursive");
353 Entry.first = Result;
354 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000355 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000356
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000357 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000358}
359
360
361/// toplevelentity
362/// ::= 'declare' FunctionHeader
363bool LLParser::ParseDeclare() {
364 assert(Lex.getKind() == lltok::kw_declare);
365 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000366
Chris Lattnerac161bf2009-01-02 07:01:27 +0000367 Function *F;
368 return ParseFunctionHeader(F, false);
369}
370
371/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000372/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000373bool LLParser::ParseDefine() {
374 assert(Lex.getKind() == lltok::kw_define);
375 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000376
Chris Lattnerac161bf2009-01-02 07:01:27 +0000377 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000378 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000379 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000380 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000381}
382
Chris Lattner3822f632009-01-02 08:05:26 +0000383/// ParseGlobalType
384/// ::= 'constant'
385/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000386bool LLParser::ParseGlobalType(bool &IsConstant) {
387 if (Lex.getKind() == lltok::kw_constant)
388 IsConstant = true;
389 else if (Lex.getKind() == lltok::kw_global)
390 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000391 else {
392 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000393 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000394 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000395 Lex.Lex();
396 return false;
397}
398
Dan Gohman466876b2009-08-12 23:32:33 +0000399/// ParseUnnamedGlobal:
400/// OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000401/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
402/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000403/// GlobalID '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000404/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
405/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000406bool LLParser::ParseUnnamedGlobal() {
407 unsigned VarID = NumberedVals.size();
408 std::string Name;
409 LocTy NameLoc = Lex.getLoc();
410
411 // Handle the GlobalID form.
412 if (Lex.getKind() == lltok::GlobalID) {
413 if (Lex.getUIntVal() != VarID)
414 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000415 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000416 Lex.Lex(); // eat GlobalID;
417
418 if (ParseToken(lltok::equal, "expected '=' after name"))
419 return true;
420 }
421
422 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000423 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000424 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000425 bool UnnamedAddr;
Dan Gohman466876b2009-08-12 23:32:33 +0000426 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000427 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000428 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000429 ParseOptionalThreadLocal(TLM) ||
430 parseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000431 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000432
Rafael Espindola464fe022014-07-30 22:51:54 +0000433 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000434 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000435 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000436 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000437 UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000438}
439
Chris Lattnerac161bf2009-01-02 07:01:27 +0000440/// ParseNamedGlobal:
441/// GlobalVar '=' OptionalVisibility ALIAS ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000442/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
443/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000444bool LLParser::ParseNamedGlobal() {
445 assert(Lex.getKind() == lltok::GlobalVar);
446 LocTy NameLoc = Lex.getLoc();
447 std::string Name = Lex.getStrVal();
448 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000449
Chris Lattnerac161bf2009-01-02 07:01:27 +0000450 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000451 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000452 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000453 bool UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000454 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
455 ParseOptionalLinkage(Linkage, HasLinkage) ||
Nico Rieck7157bb72014-01-14 15:22:47 +0000456 ParseOptionalVisibility(Visibility) ||
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000457 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000458 ParseOptionalThreadLocal(TLM) ||
459 parseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000460 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000461
Rafael Espindola464fe022014-07-30 22:51:54 +0000462 if (Lex.getKind() != lltok::kw_alias)
Nico Rieck7157bb72014-01-14 15:22:47 +0000463 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000464 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000465
466 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000467 UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000468}
469
David Majnemerdad0a642014-06-27 18:19:56 +0000470bool LLParser::parseComdat() {
471 assert(Lex.getKind() == lltok::ComdatVar);
472 std::string Name = Lex.getStrVal();
473 LocTy NameLoc = Lex.getLoc();
474 Lex.Lex();
475
476 if (ParseToken(lltok::equal, "expected '=' here"))
477 return true;
478
479 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
480 return TokError("expected comdat type");
481
482 Comdat::SelectionKind SK;
483 switch (Lex.getKind()) {
484 default:
485 return TokError("unknown selection kind");
486 case lltok::kw_any:
487 SK = Comdat::Any;
488 break;
489 case lltok::kw_exactmatch:
490 SK = Comdat::ExactMatch;
491 break;
492 case lltok::kw_largest:
493 SK = Comdat::Largest;
494 break;
495 case lltok::kw_noduplicates:
496 SK = Comdat::NoDuplicates;
497 break;
498 case lltok::kw_samesize:
499 SK = Comdat::SameSize;
500 break;
501 }
502 Lex.Lex();
503
504 // See if the comdat was forward referenced, if so, use the comdat.
505 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
506 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
507 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
508 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
509
510 Comdat *C;
511 if (I != ComdatSymTab.end())
512 C = &I->second;
513 else
514 C = M->getOrInsertComdat(Name);
515 C->setSelectionKind(SK);
516
517 return false;
518}
519
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000520// MDString:
521// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000522bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000523 std::string Str;
524 if (ParseStringConstant(Str)) return true;
Eli Bendersky5d5e18d2014-06-25 15:41:00 +0000525 llvm::UpgradeMDStringConstant(Str);
Chris Lattner1797fc72009-12-29 21:53:55 +0000526 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000527 return false;
528}
529
530// MDNode:
531// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000532bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000533 // !{ ..., !42, ... }
534 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000535 if (ParseUInt32(MID))
536 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000537
Chris Lattner8eff0152010-04-01 05:14:45 +0000538 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000539 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000540 Result = NumberedMetadata[MID];
541 return false;
542 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000543
Chris Lattner8eff0152010-04-01 05:14:45 +0000544 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000545 auto &FwdRef = ForwardRefMDNodes[MID];
546 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000547
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000548 Result = FwdRef.first.get();
549 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000550 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000551}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000552
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000553/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000554/// !foo = !{ !1, !2 }
555bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000556 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000557 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000558 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000559
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000560 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000561 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000562 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000563 return true;
564
Dan Gohman2637cc12010-07-21 23:38:33 +0000565 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000566 if (Lex.getKind() != lltok::rbrace)
567 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000568 if (ParseToken(lltok::exclaim, "Expected '!' here"))
569 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000570
Craig Topper2617dcc2014-04-15 06:32:26 +0000571 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000572 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000573 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000574 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000575
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000576 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000577}
578
Devang Patel39e64d42009-07-01 19:21:12 +0000579/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000580/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000581bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000582 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000583 Lex.Lex();
584 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000585
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000586 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000587 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000588 ParseToken(lltok::equal, "expected '=' here"))
589 return true;
590
591 // Detect common error, from old metadata syntax.
592 if (Lex.getKind() == lltok::Type)
593 return TokError("unexpected type in metadata definition");
594
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000595 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000596 if (Lex.getKind() == lltok::MetadataVar) {
597 if (ParseSpecializedMDNode(Init, IsDistinct))
598 return true;
599 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
600 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000601 return true;
602
Chris Lattnerfc58af22009-12-30 04:51:58 +0000603 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000604 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000605 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000606 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000607 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000608
Chris Lattnerfc58af22009-12-30 04:51:58 +0000609 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
610 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000611 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000612 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000613 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000614 }
615
Devang Patel39e64d42009-07-01 19:21:12 +0000616 return false;
617}
618
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000619static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
620 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
621 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
622}
623
Chris Lattnerac161bf2009-01-02 07:01:27 +0000624/// ParseAlias:
Rafael Espindola464fe022014-07-30 22:51:54 +0000625/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
626/// OptionalDLLStorageClass OptionalThreadLocal
Eric Christopher536f0a92015-05-28 23:07:39 +0000627/// OptionalUnnamedAddr 'alias' Aliasee
Rafael Espindola6b238632014-05-16 19:35:39 +0000628///
Chris Lattnerac161bf2009-01-02 07:01:27 +0000629/// Aliasee
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000630/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000631///
Eric Christopher536f0a92015-05-28 23:07:39 +0000632/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000633///
Rafael Espindola464fe022014-07-30 22:51:54 +0000634bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000635 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000636 GlobalVariable::ThreadLocalMode TLM,
637 bool UnnamedAddr) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000638 assert(Lex.getKind() == lltok::kw_alias);
639 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000640
Rafael Espindola78527052013-10-06 15:10:43 +0000641 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
642
Rafael Espindolacaa43562013-10-09 16:07:32 +0000643 if(!GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000644 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000645
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000646 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000647 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000648 "symbol with local linkage must have default visibility");
649
Rafael Espindola64c1e182014-06-03 02:41:57 +0000650 Constant *Aliasee;
651 LocTy AliaseeLoc = Lex.getLoc();
652 if (Lex.getKind() != lltok::kw_bitcast &&
653 Lex.getKind() != lltok::kw_getelementptr &&
654 Lex.getKind() != lltok::kw_addrspacecast &&
655 Lex.getKind() != lltok::kw_inttoptr) {
656 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000657 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000658 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000659 // The bitcast dest type is not present, it is implied by the dest type.
660 ValID ID;
661 if (ParseValID(ID))
662 return true;
663 if (ID.Kind != ValID::t_Constant)
664 return Error(AliaseeLoc, "invalid aliasee");
665 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000666 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000667
Rafael Espindola64c1e182014-06-03 02:41:57 +0000668 Type *AliaseeType = Aliasee->getType();
669 auto *PTy = dyn_cast<PointerType>(AliaseeType);
670 if (!PTy)
671 return Error(AliaseeLoc, "An alias must have pointer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000672
673 // Okay, create the alias but do not insert it into the module yet.
Rafael Espindola4fe00942014-05-16 13:34:04 +0000674 std::unique_ptr<GlobalAlias> GA(
David Blaikief64246b2015-04-29 21:22:39 +0000675 GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
676 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000677 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000678 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000679 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000680 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000681
Rafael Espindola54fc2982015-06-17 17:53:31 +0000682 if (Name.empty())
683 NumberedVals.push_back(GA.get());
684
Chris Lattnerac161bf2009-01-02 07:01:27 +0000685 // See if this value already exists in the symbol table. If so, it is either
686 // a redefinition or a definition of a forward reference.
Chris Lattnere38317f2009-10-25 23:22:50 +0000687 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000688 // See if this was a redefinition. If so, there is no entry in
689 // ForwardRefVals.
690 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
691 I = ForwardRefVals.find(Name);
692 if (I == ForwardRefVals.end())
693 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
694
695 // Otherwise, this was a definition of forward ref. Verify that types
696 // agree.
697 if (Val->getType() != GA->getType())
698 return Error(NameLoc,
699 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000700
Chris Lattnerac161bf2009-01-02 07:01:27 +0000701 // If they agree, just RAUW the old value with the alias and remove the
702 // forward ref info.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000703 Val->replaceAllUsesWith(GA.get());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000704 Val->eraseFromParent();
705 ForwardRefVals.erase(I);
706 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000707
Chris Lattnerac161bf2009-01-02 07:01:27 +0000708 // Insert into the module, we know its name won't collide now.
Rafael Espindolaaa273822014-05-09 21:49:17 +0000709 M->getAliasList().push_back(GA.get());
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000710 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000711
Rafael Espindolaaa273822014-05-09 21:49:17 +0000712 // The module owns this now
713 GA.release();
714
Chris Lattnerac161bf2009-01-02 07:01:27 +0000715 return false;
716}
717
718/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000719/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000720/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000721/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000722/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000723/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000724/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000725///
Eric Christopher536f0a92015-05-28 23:07:39 +0000726/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000727/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000728///
729bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
730 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000731 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000732 GlobalVariable::ThreadLocalMode TLM,
733 bool UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000734 if (!isValidVisibilityForLinkage(Visibility, Linkage))
735 return Error(NameLoc,
736 "symbol with local linkage must have default visibility");
737
Chris Lattnerac161bf2009-01-02 07:01:27 +0000738 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000739 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000740 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000741 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000742
Craig Topper2617dcc2014-04-15 06:32:26 +0000743 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000744 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000745 ParseOptionalToken(lltok::kw_externally_initialized,
746 IsExternallyInitialized,
747 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000748 ParseGlobalType(IsConstant) ||
749 ParseType(Ty, TyLoc))
750 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000751
Chris Lattnerac161bf2009-01-02 07:01:27 +0000752 // If the linkage is specified and is external, then no initializer is
753 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000754 Constant *Init = nullptr;
Nico Rieck7157bb72014-01-14 15:22:47 +0000755 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerac161bf2009-01-02 07:01:27 +0000756 Linkage != GlobalValue::ExternalLinkage)) {
757 if (ParseGlobalValue(Ty, Init))
758 return true;
759 }
760
David Majnemer49b3d9b2015-02-16 08:41:08 +0000761 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000762 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000763
David Majnemer598bd052014-12-09 05:56:09 +0000764 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000765
766 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000767 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000768 GVal = M->getNamedValue(Name);
769 if (GVal) {
Chris Lattnere38317f2009-10-25 23:22:50 +0000770 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
771 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000772 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000773 } else {
774 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
775 I = ForwardRefValIDs.find(NumberedVals.size());
776 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000777 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000778 ForwardRefValIDs.erase(I);
779 }
780 }
781
David Majnemer598bd052014-12-09 05:56:09 +0000782 GlobalVariable *GV;
783 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000784 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
785 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000786 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000787 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000788 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000789 return Error(TyLoc,
790 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000791
David Majnemer598bd052014-12-09 05:56:09 +0000792 GV = cast<GlobalVariable>(GVal);
793
Chris Lattnerac161bf2009-01-02 07:01:27 +0000794 // Move the forward-reference to the correct spot in the module.
795 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
796 }
797
798 if (Name.empty())
799 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000800
Chris Lattnerac161bf2009-01-02 07:01:27 +0000801 // Set the parsed properties on the global.
802 if (Init)
803 GV->setInitializer(Init);
804 GV->setConstant(IsConstant);
805 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
806 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000807 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000808 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000809 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000810 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000811
Chris Lattnerac161bf2009-01-02 07:01:27 +0000812 // Parse attributes on the global.
813 while (Lex.getKind() == lltok::comma) {
814 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000815
Chris Lattnerac161bf2009-01-02 07:01:27 +0000816 if (Lex.getKind() == lltok::kw_section) {
817 Lex.Lex();
818 GV->setSection(Lex.getStrVal());
819 if (ParseToken(lltok::StringConstant, "expected global section string"))
820 return true;
821 } else if (Lex.getKind() == lltok::kw_align) {
822 unsigned Alignment;
823 if (ParseOptionalAlignment(Alignment)) return true;
824 GV->setAlignment(Alignment);
825 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000826 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000827 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000828 return true;
829 if (C)
830 GV->setComdat(C);
831 else
832 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000833 }
834 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000835
Chris Lattnerac161bf2009-01-02 07:01:27 +0000836 return false;
837}
838
Bill Wendling63b88192013-02-06 06:52:58 +0000839/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000840/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000841bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000842 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000843 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000844 Lex.Lex();
845
David Majnemerb39e22b2014-12-09 18:33:57 +0000846 if (Lex.getKind() != lltok::AttrGrpID)
847 return TokError("expected attribute group id");
848
Bill Wendling63b88192013-02-06 06:52:58 +0000849 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000850 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000851 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000852 Lex.Lex();
853
854 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000855 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000856 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000857 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000858 ParseToken(lltok::rbrace, "expected end of attribute group"))
859 return true;
860
Bill Wendlingb32b0412013-02-08 06:32:06 +0000861 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000862 return Error(AttrGrpLoc, "attribute group has no attributes");
863
864 return false;
865}
866
Bill Wendling8b0321d2013-02-08 00:52:31 +0000867/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000868/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000869bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
870 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000871 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000872 bool HaveError = false;
873
874 B.clear();
875
Bill Wendling63b88192013-02-06 06:52:58 +0000876 while (true) {
877 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +0000878 if (Token == lltok::kw_builtin)
879 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +0000880 switch (Token) {
881 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000882 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +0000883 return Error(Lex.getLoc(), "unterminated attribute group");
884 case lltok::rbrace:
885 // Finished.
886 return false;
887
Bill Wendlingb32b0412013-02-08 06:32:06 +0000888 case lltok::AttrGrpID: {
889 // Allow a function to reference an attribute group:
890 //
891 // define void @foo() #1 { ... }
892 if (inAttrGrp)
893 HaveError |=
894 Error(Lex.getLoc(),
895 "cannot have an attribute group reference in an attribute group");
896
897 unsigned AttrGrpNum = Lex.getUIntVal();
898 if (inAttrGrp) break;
899
900 // Save the reference to the attribute group. We'll fill it in later.
901 FwdRefAttrGrps.push_back(AttrGrpNum);
902 break;
903 }
Bill Wendling63b88192013-02-06 06:52:58 +0000904 // Target-dependent attributes:
905 case lltok::StringConstant: {
906 std::string Attr = Lex.getStrVal();
907 Lex.Lex();
908 std::string Val;
909 if (EatIfPresent(lltok::equal) &&
910 ParseStringConstant(Val))
911 return true;
912
913 B.addAttribute(Attr, Val);
Bill Wendlingb1ea9802013-02-10 10:12:50 +0000914 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000915 }
916
917 // Target-independent attributes:
918 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +0000919 // As a hack, we allow function alignment to be initially parsed as an
920 // attribute on a function declaration/definition or added to an attribute
921 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +0000922 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000923 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000924 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000925 if (ParseToken(lltok::equal, "expected '=' here") ||
926 ParseUInt32(Alignment))
927 return true;
928 } else {
929 if (ParseOptionalAlignment(Alignment))
930 return true;
931 }
Bill Wendling63b88192013-02-06 06:52:58 +0000932 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000933 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000934 }
935 case lltok::kw_alignstack: {
936 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000937 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +0000938 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +0000939 if (ParseToken(lltok::equal, "expected '=' here") ||
940 ParseUInt32(Alignment))
941 return true;
942 } else {
943 if (ParseOptionalStackAlignment(Alignment))
944 return true;
945 }
Bill Wendling63b88192013-02-06 06:52:58 +0000946 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +0000947 continue;
Bill Wendling63b88192013-02-06 06:52:58 +0000948 }
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000949 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
Michael Gottesman41748d72013-06-27 00:25:01 +0000950 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
Diego Novilloc6399532013-05-24 12:26:52 +0000951 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
Owen Anderson85fa7d52015-05-26 23:48:40 +0000952 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000953 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000954 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000955 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
956 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
957 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
958 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
959 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
960 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
961 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
962 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
963 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
964 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000965 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000966 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
967 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
968 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
969 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
970 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
971 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
972 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000973 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
Kostya Serebryanycf880b92013-02-26 06:58:09 +0000974 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
975 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
976 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
977 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +0000978
979 // Error handling.
980 case lltok::kw_inreg:
981 case lltok::kw_signext:
982 case lltok::kw_zeroext:
983 HaveError |=
984 Error(Lex.getLoc(),
985 "invalid use of attribute on a function");
986 break;
987 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +0000988 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000989 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +0000990 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000991 case lltok::kw_nest:
992 case lltok::kw_noalias:
993 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000994 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +0000995 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +0000996 case lltok::kw_sret:
997 HaveError |=
998 Error(Lex.getLoc(),
999 "invalid use of parameter-only attribute on a function");
1000 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001001 }
1002
1003 Lex.Lex();
1004 }
1005}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001006
1007//===----------------------------------------------------------------------===//
1008// GlobalValue Reference/Resolution Routines.
1009//===----------------------------------------------------------------------===//
1010
1011/// GetGlobalVal - Get a value with the specified name or ID, creating a
1012/// forward reference record if needed. This can return null if the value
1013/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001014GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001015 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001016 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001017 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001018 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001019 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001020 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001021
Chris Lattnerac161bf2009-01-02 07:01:27 +00001022 // Look this name up in the normal function symbol table.
1023 GlobalValue *Val =
1024 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001025
Chris Lattnerac161bf2009-01-02 07:01:27 +00001026 // If this is a forward reference for the value, see if we already created a
1027 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001028 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001029 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1030 I = ForwardRefVals.find(Name);
1031 if (I != ForwardRefVals.end())
1032 Val = I->second.first;
1033 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001034
Chris Lattnerac161bf2009-01-02 07:01:27 +00001035 // If we have the value in the symbol table or fwd-ref table, return it.
1036 if (Val) {
1037 if (Val->getType() == Ty) return Val;
1038 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001039 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001040 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001041 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001042
Chris Lattnerac161bf2009-01-02 07:01:27 +00001043 // Otherwise, create a new forward reference for this value and remember it.
1044 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001045 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001046 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001047 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001048 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001049 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1050 nullptr, GlobalVariable::NotThreadLocal,
Justin Holewinski898a0a02012-11-16 21:03:47 +00001051 PTy->getAddressSpace());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001052
Chris Lattnerac161bf2009-01-02 07:01:27 +00001053 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1054 return FwdVal;
1055}
1056
Chris Lattner229907c2011-07-18 04:54:35 +00001057GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1058 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001059 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001060 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001061 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001062 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001063
Craig Topper2617dcc2014-04-15 06:32:26 +00001064 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001065
Chris Lattnerac161bf2009-01-02 07:01:27 +00001066 // If this is a forward reference for the value, see if we already created a
1067 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001068 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001069 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1070 I = ForwardRefValIDs.find(ID);
1071 if (I != ForwardRefValIDs.end())
1072 Val = I->second.first;
1073 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001074
Chris Lattnerac161bf2009-01-02 07:01:27 +00001075 // If we have the value in the symbol table or fwd-ref table, return it.
1076 if (Val) {
1077 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001078 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001079 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001080 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001081 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001082
Chris Lattnerac161bf2009-01-02 07:01:27 +00001083 // Otherwise, create a new forward reference for this value and remember it.
1084 GlobalValue *FwdVal;
Chris Lattner229907c2011-07-18 04:54:35 +00001085 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sandse2881052009-03-11 08:08:06 +00001086 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001087 else
Owen Andersonb17f3292009-07-08 19:03:57 +00001088 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
Craig Topper2617dcc2014-04-15 06:32:26 +00001089 GlobalValue::ExternalWeakLinkage, nullptr, "");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001090
Chris Lattnerac161bf2009-01-02 07:01:27 +00001091 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1092 return FwdVal;
1093}
1094
1095
1096//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001097// Comdat Reference/Resolution Routines.
1098//===----------------------------------------------------------------------===//
1099
1100Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1101 // Look this name up in the comdat symbol table.
1102 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1103 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1104 if (I != ComdatSymTab.end())
1105 return &I->second;
1106
1107 // Otherwise, create a new forward reference for this value and remember it.
1108 Comdat *C = M->getOrInsertComdat(Name);
1109 ForwardRefComdats[Name] = Loc;
1110 return C;
1111}
1112
1113
1114//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001115// Helper Routines.
1116//===----------------------------------------------------------------------===//
1117
1118/// ParseToken - If the current token has the specified kind, eat it and return
1119/// success. Otherwise, emit the specified error and return failure.
1120bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1121 if (Lex.getKind() != T)
1122 return TokError(ErrMsg);
1123 Lex.Lex();
1124 return false;
1125}
1126
Chris Lattner3822f632009-01-02 08:05:26 +00001127/// ParseStringConstant
1128/// ::= StringConstant
1129bool LLParser::ParseStringConstant(std::string &Result) {
1130 if (Lex.getKind() != lltok::StringConstant)
1131 return TokError("expected string constant");
1132 Result = Lex.getStrVal();
1133 Lex.Lex();
1134 return false;
1135}
1136
1137/// ParseUInt32
1138/// ::= uint32
1139bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001140 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1141 return TokError("expected integer");
1142 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1143 if (Val64 != unsigned(Val64))
1144 return TokError("expected 32-bit integer (too large)");
1145 Val = Val64;
1146 Lex.Lex();
1147 return false;
1148}
1149
Hal Finkelb0407ba2014-07-18 15:51:28 +00001150/// ParseUInt64
1151/// ::= uint64
1152bool LLParser::ParseUInt64(uint64_t &Val) {
1153 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1154 return TokError("expected integer");
1155 Val = Lex.getAPSIntVal().getLimitedValue();
1156 Lex.Lex();
1157 return false;
1158}
1159
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001160/// ParseTLSModel
1161/// := 'localdynamic'
1162/// := 'initialexec'
1163/// := 'localexec'
1164bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1165 switch (Lex.getKind()) {
1166 default:
1167 return TokError("expected localdynamic, initialexec or localexec");
1168 case lltok::kw_localdynamic:
1169 TLM = GlobalVariable::LocalDynamicTLSModel;
1170 break;
1171 case lltok::kw_initialexec:
1172 TLM = GlobalVariable::InitialExecTLSModel;
1173 break;
1174 case lltok::kw_localexec:
1175 TLM = GlobalVariable::LocalExecTLSModel;
1176 break;
1177 }
1178
1179 Lex.Lex();
1180 return false;
1181}
1182
1183/// ParseOptionalThreadLocal
1184/// := /*empty*/
1185/// := 'thread_local'
1186/// := 'thread_local' '(' tlsmodel ')'
1187bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1188 TLM = GlobalVariable::NotThreadLocal;
1189 if (!EatIfPresent(lltok::kw_thread_local))
1190 return false;
1191
1192 TLM = GlobalVariable::GeneralDynamicTLSModel;
1193 if (Lex.getKind() == lltok::lparen) {
1194 Lex.Lex();
1195 return ParseTLSModel(TLM) ||
1196 ParseToken(lltok::rparen, "expected ')' after thread local model");
1197 }
1198 return false;
1199}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001200
1201/// ParseOptionalAddrSpace
1202/// := /*empty*/
1203/// := 'addrspace' '(' uint32 ')'
1204bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1205 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001206 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001207 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001208 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001209 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001210 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001211}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001212
Bill Wendling34c2eb22012-12-04 23:40:58 +00001213/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1214bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1215 bool HaveError = false;
1216
1217 B.clear();
1218
1219 while (1) {
1220 lltok::Kind Token = Lex.getKind();
1221 switch (Token) {
1222 default: // End of attributes.
1223 return HaveError;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001224 case lltok::kw_align: {
1225 unsigned Alignment;
1226 if (ParseOptionalAlignment(Alignment))
1227 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001228 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001229 continue;
1230 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001231 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001232 case lltok::kw_dereferenceable: {
1233 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001234 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001235 return true;
1236 B.addDereferenceableAttr(Bytes);
1237 continue;
1238 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001239 case lltok::kw_dereferenceable_or_null: {
1240 uint64_t Bytes;
1241 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1242 return true;
1243 B.addDereferenceableOrNullAttr(Bytes);
1244 continue;
1245 }
Reid Klecknera534a382013-12-19 02:14:12 +00001246 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001247 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1248 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1249 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1250 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001251 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001252 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1253 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001254 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001255 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1256 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1257 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001258
Stephen Lin7577ed52013-04-20 13:16:13 +00001259 case lltok::kw_alignstack:
1260 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001261 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001262 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001263 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001264 case lltok::kw_minsize:
1265 case lltok::kw_naked:
1266 case lltok::kw_nobuiltin:
1267 case lltok::kw_noduplicate:
1268 case lltok::kw_noimplicitfloat:
1269 case lltok::kw_noinline:
1270 case lltok::kw_nonlazybind:
1271 case lltok::kw_noredzone:
1272 case lltok::kw_noreturn:
1273 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001274 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001275 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001276 case lltok::kw_returns_twice:
1277 case lltok::kw_sanitize_address:
1278 case lltok::kw_sanitize_memory:
1279 case lltok::kw_sanitize_thread:
1280 case lltok::kw_ssp:
1281 case lltok::kw_sspreq:
1282 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001283 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001284 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001285 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1286 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001287 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001288
Bill Wendling34c2eb22012-12-04 23:40:58 +00001289 Lex.Lex();
1290 }
1291}
1292
1293/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1294bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1295 bool HaveError = false;
1296
1297 B.clear();
1298
1299 while (1) {
1300 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001301 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001302 default: // End of attributes.
1303 return HaveError;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001304 case lltok::kw_dereferenceable: {
1305 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001306 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001307 return true;
1308 B.addDereferenceableAttr(Bytes);
1309 continue;
1310 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001311 case lltok::kw_dereferenceable_or_null: {
1312 uint64_t Bytes;
1313 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1314 return true;
1315 B.addDereferenceableOrNullAttr(Bytes);
1316 continue;
1317 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001318 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1319 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001320 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001321 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1322 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001323
Bill Wendling34c2eb22012-12-04 23:40:58 +00001324 // Error handling.
Stephen Lin7577ed52013-04-20 13:16:13 +00001325 case lltok::kw_align:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001326 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001327 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001328 case lltok::kw_nest:
1329 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001330 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001331 case lltok::kw_sret:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001332 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001333 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001334
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001335 case lltok::kw_alignstack:
1336 case lltok::kw_alwaysinline:
Michael Gottesman41748d72013-06-27 00:25:01 +00001337 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001338 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001339 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001340 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001341 case lltok::kw_minsize:
1342 case lltok::kw_naked:
1343 case lltok::kw_nobuiltin:
1344 case lltok::kw_noduplicate:
1345 case lltok::kw_noimplicitfloat:
1346 case lltok::kw_noinline:
1347 case lltok::kw_nonlazybind:
1348 case lltok::kw_noredzone:
1349 case lltok::kw_noreturn:
1350 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001351 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001352 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001353 case lltok::kw_returns_twice:
1354 case lltok::kw_sanitize_address:
1355 case lltok::kw_sanitize_memory:
1356 case lltok::kw_sanitize_thread:
1357 case lltok::kw_ssp:
1358 case lltok::kw_sspreq:
1359 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001360 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001361 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001362 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001363 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001364
1365 case lltok::kw_readnone:
1366 case lltok::kw_readonly:
1367 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001368 }
1369
Chris Lattnerac161bf2009-01-02 07:01:27 +00001370 Lex.Lex();
1371 }
1372}
1373
1374/// ParseOptionalLinkage
1375/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001376/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001377/// ::= 'internal'
1378/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001379/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001380/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001381/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001382/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001383/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001384/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001385/// ::= 'extern_weak'
1386/// ::= 'external'
1387bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1388 HasLinkage = false;
1389 switch (Lex.getKind()) {
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001390 default: Res=GlobalValue::ExternalLinkage; return false;
1391 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001392 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1393 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1394 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1395 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1396 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner184f1be2009-04-13 05:44:34 +00001397 case lltok::kw_available_externally:
1398 Res = GlobalValue::AvailableExternallyLinkage;
1399 break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001400 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001401 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +00001402 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1403 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001404 }
1405 Lex.Lex();
1406 HasLinkage = true;
1407 return false;
1408}
1409
1410/// ParseOptionalVisibility
1411/// ::= /*empty*/
1412/// ::= 'default'
1413/// ::= 'hidden'
1414/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001415///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001416bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1417 switch (Lex.getKind()) {
1418 default: Res = GlobalValue::DefaultVisibility; return false;
1419 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1420 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1421 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1422 }
1423 Lex.Lex();
1424 return false;
1425}
1426
Nico Rieck7157bb72014-01-14 15:22:47 +00001427/// ParseOptionalDLLStorageClass
1428/// ::= /*empty*/
1429/// ::= 'dllimport'
1430/// ::= 'dllexport'
1431///
1432bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1433 switch (Lex.getKind()) {
1434 default: Res = GlobalValue::DefaultStorageClass; return false;
1435 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1436 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1437 }
1438 Lex.Lex();
1439 return false;
1440}
1441
Chris Lattnerac161bf2009-01-02 07:01:27 +00001442/// ParseOptionalCallingConv
1443/// ::= /*empty*/
1444/// ::= 'ccc'
1445/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001446/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001447/// ::= 'coldcc'
1448/// ::= 'x86_stdcallcc'
1449/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001450/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001451/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001452/// ::= 'arm_apcscc'
1453/// ::= 'arm_aapcscc'
1454/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001455/// ::= 'msp430_intrcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001456/// ::= 'ptx_kernel'
1457/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001458/// ::= 'spir_func'
1459/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001460/// ::= 'x86_64_sysvcc'
1461/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001462/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001463/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001464/// ::= 'preserve_mostcc'
1465/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001466/// ::= 'ghccc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001467/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001468///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001469bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001470 switch (Lex.getKind()) {
1471 default: CC = CallingConv::C; return false;
1472 case lltok::kw_ccc: CC = CallingConv::C; break;
1473 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1474 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1475 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1476 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001477 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001478 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001479 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1480 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1481 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001482 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001483 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1484 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001485 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1486 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001487 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001488 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1489 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001490 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001491 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001492 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1493 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001494 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001495 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001496 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001497 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001498 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001499 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001500
Chris Lattnerac161bf2009-01-02 07:01:27 +00001501 Lex.Lex();
1502 return false;
1503}
1504
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001505/// ParseMetadataAttachment
1506/// ::= !dbg !42
1507bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1508 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1509
1510 std::string Name = Lex.getStrVal();
1511 Kind = M->getMDKindID(Name);
1512 Lex.Lex();
1513
1514 return ParseMDNode(MD);
1515}
1516
Chris Lattner5c427632009-12-30 05:31:19 +00001517/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001518/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001519bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001520 do {
1521 if (Lex.getKind() != lltok::MetadataVar)
1522 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001523
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001524 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001525 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001526 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001527 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001528
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001529 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001530 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001531 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001532
Chris Lattner596760d2009-12-29 21:25:40 +00001533 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001534 } while (EatIfPresent(lltok::comma));
1535 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001536}
1537
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001538/// ParseOptionalFunctionMetadata
1539/// ::= (!dbg !57)*
1540bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1541 while (Lex.getKind() == lltok::MetadataVar) {
1542 unsigned MDK;
1543 MDNode *N;
1544 if (ParseMetadataAttachment(MDK, N))
1545 return true;
1546
1547 F.setMetadata(MDK, N);
1548 }
1549 return false;
1550}
1551
Chris Lattnerac161bf2009-01-02 07:01:27 +00001552/// ParseOptionalAlignment
1553/// ::= /* empty */
1554/// ::= 'align' 4
1555bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1556 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001557 if (!EatIfPresent(lltok::kw_align))
1558 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001559 LocTy AlignLoc = Lex.getLoc();
1560 if (ParseUInt32(Alignment)) return true;
1561 if (!isPowerOf2_32(Alignment))
1562 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001563 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001564 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001565 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001566}
1567
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001568/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001569/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001570/// ::= AttrKind '(' 4 ')'
1571///
1572/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1573bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1574 uint64_t &Bytes) {
1575 assert((AttrKind == lltok::kw_dereferenceable ||
1576 AttrKind == lltok::kw_dereferenceable_or_null) &&
1577 "contract!");
1578
Hal Finkelb0407ba2014-07-18 15:51:28 +00001579 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001580 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001581 return false;
1582 LocTy ParenLoc = Lex.getLoc();
1583 if (!EatIfPresent(lltok::lparen))
1584 return Error(ParenLoc, "expected '('");
1585 LocTy DerefLoc = Lex.getLoc();
1586 if (ParseUInt64(Bytes)) return true;
1587 ParenLoc = Lex.getLoc();
1588 if (!EatIfPresent(lltok::rparen))
1589 return Error(ParenLoc, "expected ')'");
1590 if (!Bytes)
1591 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1592 return false;
1593}
1594
Chris Lattnerb2f39502009-12-30 05:44:30 +00001595/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001596/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001597/// ::= ',' align 4
1598///
1599/// This returns with AteExtraComma set to true if it ate an excess comma at the
1600/// end.
1601bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1602 bool &AteExtraComma) {
1603 AteExtraComma = false;
1604 while (EatIfPresent(lltok::comma)) {
1605 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001606 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001607 AteExtraComma = true;
1608 return false;
1609 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001610
Chris Lattner95b0ff42010-04-23 00:50:50 +00001611 if (Lex.getKind() != lltok::kw_align)
1612 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001613
Chris Lattner95b0ff42010-04-23 00:50:50 +00001614 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001615 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001616
Devang Patelea8a4b92009-09-17 23:04:48 +00001617 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001618}
1619
Eli Friedmanfee02c62011-07-25 23:16:38 +00001620/// ParseScopeAndOrdering
1621/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1622/// else: ::=
1623///
1624/// This sets Scope and Ordering to the parsed values.
1625bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1626 AtomicOrdering &Ordering) {
1627 if (!isAtomic)
1628 return false;
1629
1630 Scope = CrossThread;
1631 if (EatIfPresent(lltok::kw_singlethread))
1632 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001633
1634 return ParseOrdering(Ordering);
1635}
1636
1637/// ParseOrdering
1638/// ::= AtomicOrdering
1639///
1640/// This sets Ordering to the parsed value.
1641bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001642 switch (Lex.getKind()) {
1643 default: return TokError("Expected ordering on atomic instruction");
1644 case lltok::kw_unordered: Ordering = Unordered; break;
1645 case lltok::kw_monotonic: Ordering = Monotonic; break;
1646 case lltok::kw_acquire: Ordering = Acquire; break;
1647 case lltok::kw_release: Ordering = Release; break;
1648 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1649 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1650 }
1651 Lex.Lex();
1652 return false;
1653}
1654
Charles Davisbe5557e2010-02-12 00:31:15 +00001655/// ParseOptionalStackAlignment
1656/// ::= /* empty */
1657/// ::= 'alignstack' '(' 4 ')'
1658bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1659 Alignment = 0;
1660 if (!EatIfPresent(lltok::kw_alignstack))
1661 return false;
1662 LocTy ParenLoc = Lex.getLoc();
1663 if (!EatIfPresent(lltok::lparen))
1664 return Error(ParenLoc, "expected '('");
1665 LocTy AlignLoc = Lex.getLoc();
1666 if (ParseUInt32(Alignment)) return true;
1667 ParenLoc = Lex.getLoc();
1668 if (!EatIfPresent(lltok::rparen))
1669 return Error(ParenLoc, "expected ')'");
1670 if (!isPowerOf2_32(Alignment))
1671 return Error(AlignLoc, "stack alignment is not a power of two");
1672 return false;
1673}
Devang Patelea8a4b92009-09-17 23:04:48 +00001674
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001675/// ParseIndexList - This parses the index list for an insert/extractvalue
1676/// instruction. This sets AteExtraComma in the case where we eat an extra
1677/// comma at the end of the line and find that it is followed by metadata.
1678/// Clients that don't allow metadata can call the version of this function that
1679/// only takes one argument.
1680///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001681/// ParseIndexList
1682/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001683///
1684bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1685 bool &AteExtraComma) {
1686 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001687
Chris Lattnerac161bf2009-01-02 07:01:27 +00001688 if (Lex.getKind() != lltok::comma)
1689 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001690
Chris Lattner3822f632009-01-02 08:05:26 +00001691 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001692 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001693 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001694 AteExtraComma = true;
1695 return false;
1696 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001697 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001698 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001699 Indices.push_back(Idx);
1700 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001701
Chris Lattnerac161bf2009-01-02 07:01:27 +00001702 return false;
1703}
1704
1705//===----------------------------------------------------------------------===//
1706// Type Parsing.
1707//===----------------------------------------------------------------------===//
1708
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001709/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001710bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001711 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001712 switch (Lex.getKind()) {
1713 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001714 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001715 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001716 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001717 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001718 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001719 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001720 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001721 // Type ::= StructType
1722 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001723 return true;
1724 break;
1725 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001726 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001727 Lex.Lex(); // eat the lsquare.
1728 if (ParseArrayVectorType(Result, false))
1729 return true;
1730 break;
1731 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001732 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00001733 Lex.Lex();
1734 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001735 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00001736 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001737 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001738 } else if (ParseArrayVectorType(Result, true))
1739 return true;
1740 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001741 case lltok::LocalVar: {
1742 // Type ::= %foo
1743 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001744
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001745 // If the type hasn't been defined yet, create a forward definition and
1746 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001747 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001748 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001749 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001750 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001751 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001752 Lex.Lex();
1753 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001754 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001755
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001756 case lltok::LocalVarID: {
1757 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001758 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001759
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001760 // If the type hasn't been defined yet, create a forward definition and
1761 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00001762 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00001763 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001764 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001765 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001766 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001767 Lex.Lex();
1768 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001769 }
1770 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001771
1772 // Parse the type suffixes.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001773 while (1) {
1774 switch (Lex.getKind()) {
1775 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001776 default:
1777 if (!AllowVoid && Result->isVoidTy())
1778 return Error(TypeLoc, "void type only allowed for function results");
1779 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001780
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001781 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001782 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001783 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001784 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001785 if (Result->isVoidTy())
1786 return TokError("pointers to void are invalid - use i8* instead");
1787 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001788 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001789 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001790 Lex.Lex();
1791 break;
1792
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001793 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001794 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001795 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00001796 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001797 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00001798 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001799 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001800 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001801 unsigned AddrSpace;
1802 if (ParseOptionalAddrSpace(AddrSpace) ||
1803 ParseToken(lltok::star, "expected '*' in address space"))
1804 return true;
1805
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001806 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001807 break;
1808 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001809
Chris Lattnerac161bf2009-01-02 07:01:27 +00001810 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1811 case lltok::lparen:
1812 if (ParseFunctionType(Result))
1813 return true;
1814 break;
1815 }
1816 }
1817}
1818
1819/// ParseParameterList
1820/// ::= '(' ')'
1821/// ::= '(' Arg (',' Arg)* ')'
1822/// Arg
1823/// ::= Type OptionalAttributes Value OptionalAttributes
1824bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00001825 PerFunctionState &PFS, bool IsMustTailCall,
1826 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001827 if (ParseToken(lltok::lparen, "expected '(' in call"))
1828 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001829
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001830 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001831 while (Lex.getKind() != lltok::rparen) {
1832 // If this isn't the first argument, we need a comma.
1833 if (!ArgList.empty() &&
1834 ParseToken(lltok::comma, "expected ',' in argument list"))
1835 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001836
Reid Kleckner83498642014-08-26 00:33:28 +00001837 // Parse an ellipsis if this is a musttail call in a variadic function.
1838 if (Lex.getKind() == lltok::dotdotdot) {
1839 const char *Msg = "unexpected ellipsis in argument list for ";
1840 if (!IsMustTailCall)
1841 return TokError(Twine(Msg) + "non-musttail call");
1842 if (!InVarArgsFunc)
1843 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1844 Lex.Lex(); // Lex the '...', it is purely for readability.
1845 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1846 }
1847
Chris Lattnerac161bf2009-01-02 07:01:27 +00001848 // Parse the argument.
1849 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00001850 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001851 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001852 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00001853 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001854 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00001855
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001856 if (ArgTy->isMetadataTy()) {
1857 if (ParseMetadataAsValue(V, PFS))
1858 return true;
1859 } else {
1860 // Otherwise, handle normal operands.
1861 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1862 return true;
1863 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001864 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1865 AttrIndex++,
1866 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001867 }
1868
Reid Kleckner83498642014-08-26 00:33:28 +00001869 if (IsMustTailCall && InVarArgsFunc)
1870 return TokError("expected '...' at end of argument list for musttail call "
1871 "in varargs function");
1872
Chris Lattnerac161bf2009-01-02 07:01:27 +00001873 Lex.Lex(); // Lex the ')'.
1874 return false;
1875}
1876
1877
1878
Chris Lattner2ed06b42009-01-05 18:34:07 +00001879/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001880/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00001881/// ::= '(' ArgTypeListI ')'
1882/// ArgTypeListI
1883/// ::= /*empty*/
1884/// ::= '...'
1885/// ::= ArgTypeList ',' '...'
1886/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00001887///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001888bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1889 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00001890 isVarArg = false;
1891 assert(Lex.getKind() == lltok::lparen);
1892 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001893
Chris Lattnerac161bf2009-01-02 07:01:27 +00001894 if (Lex.getKind() == lltok::rparen) {
1895 // empty
1896 } else if (Lex.getKind() == lltok::dotdotdot) {
1897 isVarArg = true;
1898 Lex.Lex();
1899 } else {
1900 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00001901 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00001902 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001903 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001904
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001905 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00001906 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001907
Chris Lattnerfdd87902009-10-05 05:54:46 +00001908 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001909 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001910
Chris Lattnerdef19492011-06-17 06:36:20 +00001911 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001912 Name = Lex.getStrVal();
1913 Lex.Lex();
1914 }
Chris Lattner3822f632009-01-02 08:05:26 +00001915
Nick Lewycky0aa6a742009-06-07 07:26:46 +00001916 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00001917 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001918
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001919 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001920 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
1921 AttrIndex++, Attrs),
1922 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001923
Chris Lattner3822f632009-01-02 08:05:26 +00001924 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001925 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00001926 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001927 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001928 break;
1929 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001930
Chris Lattnerac161bf2009-01-02 07:01:27 +00001931 // Otherwise must be an argument type.
1932 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00001933 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00001934
Chris Lattnerfdd87902009-10-05 05:54:46 +00001935 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00001936 return Error(TypeLoc, "argument can not have void type");
1937
Chris Lattnerdef19492011-06-17 06:36:20 +00001938 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001939 Name = Lex.getStrVal();
1940 Lex.Lex();
1941 } else {
1942 Name = "";
1943 }
Chris Lattner3822f632009-01-02 08:05:26 +00001944
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001945 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00001946 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001947
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001948 ArgList.emplace_back(
1949 TypeLoc, ArgTy,
1950 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
1951 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00001952 }
1953 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001954
Chris Lattner3822f632009-01-02 08:05:26 +00001955 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001956}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001957
Chris Lattnerac161bf2009-01-02 07:01:27 +00001958/// ParseFunctionType
1959/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001960bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001961 assert(Lex.getKind() == lltok::lparen);
1962
Chris Lattnerce473c72009-01-05 08:04:33 +00001963 if (!FunctionType::isValidReturnType(Result))
1964 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001965
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001966 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001967 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001968 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001969 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001970
Chris Lattnerac161bf2009-01-02 07:01:27 +00001971 // Reject names on the arguments lists.
1972 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1973 if (!ArgList[i].Name.empty())
1974 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00001975 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00001976 return Error(ArgList[i].Loc,
1977 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001978 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001979
Jay Foadb804a2b2011-07-12 14:06:48 +00001980 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001981 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001982 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001983
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001984 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001985 return false;
1986}
1987
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001988/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1989/// other structs.
1990bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1991 SmallVector<Type*, 8> Elts;
1992 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001993
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001994 Result = StructType::get(Context, Elts, Packed);
1995 return false;
1996}
1997
1998/// ParseStructDefinition - Parse a struct in a 'type' definition.
1999bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2000 std::pair<Type*, LocTy> &Entry,
2001 Type *&ResultTy) {
2002 // If the type was already defined, diagnose the redefinition.
2003 if (Entry.first && !Entry.second.isValid())
2004 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002005
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002006 // If we have opaque, just return without filling in the definition for the
2007 // struct. This counts as a definition as far as the .ll file goes.
2008 if (EatIfPresent(lltok::kw_opaque)) {
2009 // This type is being defined, so clear the location to indicate this.
2010 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002011
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002012 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002013 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002014 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002015 ResultTy = Entry.first;
2016 return false;
2017 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002018
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002019 // If the type starts with '<', then it is either a packed struct or a vector.
2020 bool isPacked = EatIfPresent(lltok::less);
2021
2022 // If we don't have a struct, then we have a random type alias, which we
2023 // accept for compatibility with old files. These types are not allowed to be
2024 // forward referenced and not allowed to be recursive.
2025 if (Lex.getKind() != lltok::lbrace) {
2026 if (Entry.first)
2027 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002028
Craig Topper2617dcc2014-04-15 06:32:26 +00002029 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002030 if (isPacked)
2031 return ParseArrayVectorType(ResultTy, true);
2032 return ParseType(ResultTy);
2033 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002034
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002035 // This type is being defined, so clear the location to indicate this.
2036 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002037
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002038 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002039 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002040 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002041
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002042 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002043
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002044 SmallVector<Type*, 8> Body;
2045 if (ParseStructBody(Body) ||
2046 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2047 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002048
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002049 STy->setBody(Body, isPacked);
2050 ResultTy = STy;
2051 return false;
2052}
2053
2054
Chris Lattnerac161bf2009-01-02 07:01:27 +00002055/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002056/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002057/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002058/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002059/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002060/// ::= '<' '{' Type (',' Type)* '}' '>'
2061bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002062 assert(Lex.getKind() == lltok::lbrace);
2063 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002064
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002065 // Handle the empty struct.
2066 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002067 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002068
Chris Lattnerf880ca22009-03-09 04:49:14 +00002069 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002070 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002071 if (ParseType(Ty)) return true;
2072 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002073
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002074 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002075 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002076
Chris Lattner3822f632009-01-02 08:05:26 +00002077 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002078 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002079 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002080
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002081 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002082 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002083
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002084 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002085 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002086
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002087 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002088}
2089
2090/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2091/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002092/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002093/// ::= '[' APSINTVAL 'x' Types ']'
2094/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002095bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002096 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2097 Lex.getAPSIntVal().getBitWidth() > 64)
2098 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002099
Chris Lattnerac161bf2009-01-02 07:01:27 +00002100 LocTy SizeLoc = Lex.getLoc();
2101 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002102 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002103
Chris Lattner3822f632009-01-02 08:05:26 +00002104 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2105 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002106
2107 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002108 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002109 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002110
Chris Lattner3822f632009-01-02 08:05:26 +00002111 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2112 "expected end of sequential type"))
2113 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002114
Chris Lattnerac161bf2009-01-02 07:01:27 +00002115 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002116 if (Size == 0)
2117 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002118 if ((unsigned)Size != Size)
2119 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002120 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002121 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002122 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002123 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002124 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002126 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002127 }
2128 return false;
2129}
2130
2131//===----------------------------------------------------------------------===//
2132// Function Semantic Analysis.
2133//===----------------------------------------------------------------------===//
2134
Chris Lattner3432c622009-10-28 03:39:23 +00002135LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2136 int functionNumber)
2137 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002138
2139 // Insert unnamed arguments into the NumberedVals list.
2140 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2141 AI != E; ++AI)
2142 if (!AI->hasName())
2143 NumberedVals.push_back(AI);
2144}
2145
2146LLParser::PerFunctionState::~PerFunctionState() {
2147 // If there were any forward referenced non-basicblock values, delete them.
2148 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2149 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2150 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002151 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002152 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002153 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002154 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002155 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002156
Chris Lattnerac161bf2009-01-02 07:01:27 +00002157 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2158 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2159 if (!isa<BasicBlock>(I->second.first)) {
Owen Anderson09063ce2009-07-02 17:04:01 +00002160 I->second.first->replaceAllUsesWith(
Owen Andersonb292b8c2009-07-30 23:03:37 +00002161 UndefValue::get(I->second.first->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002162 delete I->second.first;
Craig Topper2617dcc2014-04-15 06:32:26 +00002163 I->second.first = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002164 }
2165}
2166
Chris Lattner3432c622009-10-28 03:39:23 +00002167bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002168 if (!ForwardRefVals.empty())
2169 return P.Error(ForwardRefVals.begin()->second.second,
2170 "use of undefined value '%" + ForwardRefVals.begin()->first +
2171 "'");
2172 if (!ForwardRefValIDs.empty())
2173 return P.Error(ForwardRefValIDs.begin()->second.second,
2174 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002175 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002176 return false;
2177}
2178
2179
2180/// GetVal - Get a value with the specified name or ID, creating a
2181/// forward reference record if needed. This can return null if the value
2182/// exists but does not have the right type.
2183Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattner229907c2011-07-18 04:54:35 +00002184 Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002185 // Look this name up in the normal function symbol table.
2186 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002187
Chris Lattnerac161bf2009-01-02 07:01:27 +00002188 // If this is a forward reference for the value, see if we already created a
2189 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002190 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002191 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2192 I = ForwardRefVals.find(Name);
2193 if (I != ForwardRefVals.end())
2194 Val = I->second.first;
2195 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002196
Chris Lattnerac161bf2009-01-02 07:01:27 +00002197 // If we have the value in the symbol table or fwd-ref table, return it.
2198 if (Val) {
2199 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002200 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002201 P.Error(Loc, "'%" + Name + "' is not a basic block");
2202 else
2203 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002204 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002205 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002206 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002207
Chris Lattnerac161bf2009-01-02 07:01:27 +00002208 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002209 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002210 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002211 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002212 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002213
Chris Lattnerac161bf2009-01-02 07:01:27 +00002214 // Otherwise, create a new forward reference for this value and remember it.
2215 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002216 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002217 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002218 else
2219 FwdVal = new Argument(Ty, Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002220
Chris Lattnerac161bf2009-01-02 07:01:27 +00002221 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2222 return FwdVal;
2223}
2224
Chris Lattner229907c2011-07-18 04:54:35 +00002225Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00002226 LocTy Loc) {
2227 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002228 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002229
Chris Lattnerac161bf2009-01-02 07:01:27 +00002230 // If this is a forward reference for the value, see if we already created a
2231 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002232 if (!Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002233 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2234 I = ForwardRefValIDs.find(ID);
2235 if (I != ForwardRefValIDs.end())
2236 Val = I->second.first;
2237 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002238
Chris Lattnerac161bf2009-01-02 07:01:27 +00002239 // If we have the value in the symbol table or fwd-ref table, return it.
2240 if (Val) {
2241 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002242 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002243 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002244 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002245 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002246 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002247 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002248 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002249
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002250 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002251 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002252 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002253 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002254
Chris Lattnerac161bf2009-01-02 07:01:27 +00002255 // Otherwise, create a new forward reference for this value and remember it.
2256 Value *FwdVal;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002257 if (Ty->isLabelTy())
Owen Anderson55f1c092009-08-13 21:58:54 +00002258 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002259 else
2260 FwdVal = new Argument(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002261
Chris Lattnerac161bf2009-01-02 07:01:27 +00002262 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2263 return FwdVal;
2264}
2265
2266/// SetInstName - After an instruction is parsed and inserted into its
2267/// basic block, this installs its name.
2268bool LLParser::PerFunctionState::SetInstName(int NameID,
2269 const std::string &NameStr,
2270 LocTy NameLoc, Instruction *Inst) {
2271 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002272 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002273 if (NameID != -1 || !NameStr.empty())
2274 return P.Error(NameLoc, "instructions returning void cannot have a name");
2275 return false;
2276 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002277
Chris Lattnerac161bf2009-01-02 07:01:27 +00002278 // If this was a numbered instruction, verify that the instruction is the
2279 // expected value and resolve any forward references.
2280 if (NameStr.empty()) {
2281 // If neither a name nor an ID was specified, just use the next ID.
2282 if (NameID == -1)
2283 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002284
Chris Lattnerac161bf2009-01-02 07:01:27 +00002285 if (unsigned(NameID) != NumberedVals.size())
2286 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002287 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002288
Chris Lattnerac161bf2009-01-02 07:01:27 +00002289 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2290 ForwardRefValIDs.find(NameID);
2291 if (FI != ForwardRefValIDs.end()) {
2292 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002293 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002294 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002295 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2baa6a32009-09-02 15:02:57 +00002296 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002297 ForwardRefValIDs.erase(FI);
2298 }
2299
2300 NumberedVals.push_back(Inst);
2301 return false;
2302 }
2303
2304 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2305 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2306 FI = ForwardRefVals.find(NameStr);
2307 if (FI != ForwardRefVals.end()) {
2308 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002309 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002310 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002311 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2fcee702009-09-02 14:22:03 +00002312 delete FI->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002313 ForwardRefVals.erase(FI);
2314 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002315
Chris Lattnerac161bf2009-01-02 07:01:27 +00002316 // Set the name on the instruction.
2317 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002318
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002319 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002320 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002321 NameStr + "'");
2322 return false;
2323}
2324
2325/// GetBB - Get a basic block with the specified name or ID, creating a
2326/// forward reference record if needed.
2327BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2328 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002329 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2330 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002331}
2332
2333BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002334 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2335 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002336}
2337
2338/// DefineBB - Define the specified basic block, which is either named or
2339/// unnamed. If there is an error, this returns null otherwise it returns
2340/// the block being defined.
2341BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2342 LocTy Loc) {
2343 BasicBlock *BB;
2344 if (Name.empty())
2345 BB = GetBB(NumberedVals.size(), Loc);
2346 else
2347 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002348 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002349
Chris Lattnerac161bf2009-01-02 07:01:27 +00002350 // Move the block to the end of the function. Forward ref'd blocks are
2351 // inserted wherever they happen to be referenced.
2352 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002353
Chris Lattnerac161bf2009-01-02 07:01:27 +00002354 // Remove the block from forward ref sets.
2355 if (Name.empty()) {
2356 ForwardRefValIDs.erase(NumberedVals.size());
2357 NumberedVals.push_back(BB);
2358 } else {
2359 // BB forward references are already in the function symbol table.
2360 ForwardRefVals.erase(Name);
2361 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002362
Chris Lattnerac161bf2009-01-02 07:01:27 +00002363 return BB;
2364}
2365
2366//===----------------------------------------------------------------------===//
2367// Constants.
2368//===----------------------------------------------------------------------===//
2369
2370/// ParseValID - Parse an abstract value that doesn't necessarily have a
2371/// type implied. For example, if we parse "4" we don't know what integer type
2372/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002373/// sanity. PFS is used to convert function-local operands of metadata (since
2374/// metadata operands are not just parsed here but also converted to values).
2375/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002376bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002377 ID.Loc = Lex.getLoc();
2378 switch (Lex.getKind()) {
2379 default: return TokError("expected value token");
2380 case lltok::GlobalID: // @42
2381 ID.UIntVal = Lex.getUIntVal();
2382 ID.Kind = ValID::t_GlobalID;
2383 break;
2384 case lltok::GlobalVar: // @foo
2385 ID.StrVal = Lex.getStrVal();
2386 ID.Kind = ValID::t_GlobalName;
2387 break;
2388 case lltok::LocalVarID: // %42
2389 ID.UIntVal = Lex.getUIntVal();
2390 ID.Kind = ValID::t_LocalID;
2391 break;
2392 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002393 ID.StrVal = Lex.getStrVal();
2394 ID.Kind = ValID::t_LocalName;
2395 break;
2396 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002397 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002398 ID.Kind = ValID::t_APSInt;
2399 break;
2400 case lltok::APFloat:
2401 ID.APFloatVal = Lex.getAPFloatVal();
2402 ID.Kind = ValID::t_APFloat;
2403 break;
2404 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002405 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002406 ID.Kind = ValID::t_Constant;
2407 break;
2408 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002409 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002410 ID.Kind = ValID::t_Constant;
2411 break;
2412 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2413 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2414 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002415
Chris Lattnerac161bf2009-01-02 07:01:27 +00002416 case lltok::lbrace: {
2417 // ValID ::= '{' ConstVector '}'
2418 Lex.Lex();
2419 SmallVector<Constant*, 16> Elts;
2420 if (ParseGlobalValueVector(Elts) ||
2421 ParseToken(lltok::rbrace, "expected end of struct constant"))
2422 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002423
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002424 ID.ConstantStructElts = new Constant*[Elts.size()];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002425 ID.UIntVal = Elts.size();
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002426 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002427 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002428 return false;
2429 }
2430 case lltok::less: {
2431 // ValID ::= '<' ConstVector '>' --> Vector.
2432 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2433 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002434 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002435
Chris Lattnerac161bf2009-01-02 07:01:27 +00002436 SmallVector<Constant*, 16> Elts;
2437 LocTy FirstEltLoc = Lex.getLoc();
2438 if (ParseGlobalValueVector(Elts) ||
2439 (isPackedStruct &&
2440 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2441 ParseToken(lltok::greater, "expected end of constant"))
2442 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002443
Chris Lattnerac161bf2009-01-02 07:01:27 +00002444 if (isPackedStruct) {
Reid Kleckner2ae03e12015-03-04 18:31:10 +00002445 ID.ConstantStructElts = new Constant*[Elts.size()];
2446 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002447 ID.UIntVal = Elts.size();
2448 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002449 return false;
2450 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002451
Chris Lattnerac161bf2009-01-02 07:01:27 +00002452 if (Elts.empty())
2453 return Error(ID.Loc, "constant vector must not be empty");
2454
Duncan Sands9dff9be2010-02-15 16:12:20 +00002455 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002456 !Elts[0]->getType()->isFloatingPointTy() &&
2457 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002458 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002459 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002460
Chris Lattnerac161bf2009-01-02 07:01:27 +00002461 // Verify that all the vector elements have the same type.
2462 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2463 if (Elts[i]->getType() != Elts[0]->getType())
2464 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002465 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002466 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002467
Chris Lattner69229312011-02-15 00:14:00 +00002468 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002469 ID.Kind = ValID::t_Constant;
2470 return false;
2471 }
2472 case lltok::lsquare: { // Array Constant
2473 Lex.Lex();
2474 SmallVector<Constant*, 16> Elts;
2475 LocTy FirstEltLoc = Lex.getLoc();
2476 if (ParseGlobalValueVector(Elts) ||
2477 ParseToken(lltok::rsquare, "expected end of array constant"))
2478 return true;
2479
2480 // Handle empty element.
2481 if (Elts.empty()) {
2482 // Use undef instead of an array because it's inconvenient to determine
2483 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002484 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002485 return false;
2486 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002487
Chris Lattnerac161bf2009-01-02 07:01:27 +00002488 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002489 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002490 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002491
Owen Anderson4056ca92009-07-29 22:17:13 +00002492 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002493
Chris Lattnerac161bf2009-01-02 07:01:27 +00002494 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002495 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002496 if (Elts[i]->getType() != Elts[0]->getType())
2497 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002498 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002499 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002500 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002501
Jay Foad83be3612011-06-22 09:24:39 +00002502 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002503 ID.Kind = ValID::t_Constant;
2504 return false;
2505 }
2506 case lltok::kw_c: // c "foo"
2507 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002508 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2509 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002510 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2511 ID.Kind = ValID::t_Constant;
2512 return false;
2513
2514 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002515 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2516 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002517 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002518 Lex.Lex();
2519 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002520 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002521 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002522 ParseStringConstant(ID.StrVal) ||
2523 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002524 ParseToken(lltok::StringConstant, "expected constraint string"))
2525 return true;
2526 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002527 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002528 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002529 ID.Kind = ValID::t_InlineAsm;
2530 return false;
2531 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002532
Chris Lattner3432c622009-10-28 03:39:23 +00002533 case lltok::kw_blockaddress: {
2534 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2535 Lex.Lex();
2536
2537 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002538
Chris Lattner3432c622009-10-28 03:39:23 +00002539 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2540 ParseValID(Fn) ||
2541 ParseToken(lltok::comma, "expected comma in block address expression")||
2542 ParseValID(Label) ||
2543 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2544 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002545
Chris Lattner3432c622009-10-28 03:39:23 +00002546 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2547 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002548 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002549 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002550
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002551 // Try to find the function (but skip it if it's forward-referenced).
2552 GlobalValue *GV = nullptr;
2553 if (Fn.Kind == ValID::t_GlobalID) {
2554 if (Fn.UIntVal < NumberedVals.size())
2555 GV = NumberedVals[Fn.UIntVal];
2556 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2557 GV = M->getNamedValue(Fn.StrVal);
2558 }
2559 Function *F = nullptr;
2560 if (GV) {
2561 // Confirm that it's actually a function with a definition.
2562 if (!isa<Function>(GV))
2563 return Error(Fn.Loc, "expected function name in blockaddress");
2564 F = cast<Function>(GV);
2565 if (F->isDeclaration())
2566 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2567 }
2568
2569 if (!F) {
2570 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002571 GlobalValue *&FwdRef =
2572 ForwardRefBlockAddresses.insert(std::make_pair(
2573 std::move(Fn),
2574 std::map<ValID, GlobalValue *>()))
2575 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2576 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002577 if (!FwdRef)
2578 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2579 GlobalValue::InternalLinkage, nullptr, "");
2580 ID.ConstantVal = FwdRef;
2581 ID.Kind = ValID::t_Constant;
2582 return false;
2583 }
2584
2585 // We found the function; now find the basic block. Don't use PFS, since we
2586 // might be inside a constant expression.
2587 BasicBlock *BB;
2588 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2589 if (Label.Kind == ValID::t_LocalID)
2590 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2591 else
2592 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2593 if (!BB)
2594 return Error(Label.Loc, "referenced value is not a basic block");
2595 } else {
2596 if (Label.Kind == ValID::t_LocalID)
2597 return Error(Label.Loc, "cannot take address of numeric label after "
2598 "the function is defined");
2599 BB = dyn_cast_or_null<BasicBlock>(
2600 F->getValueSymbolTable().lookup(Label.StrVal));
2601 if (!BB)
2602 return Error(Label.Loc, "referenced value is not a basic block");
2603 }
2604
2605 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002606 ID.Kind = ValID::t_Constant;
2607 return false;
2608 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002609
Chris Lattnerac161bf2009-01-02 07:01:27 +00002610 case lltok::kw_trunc:
2611 case lltok::kw_zext:
2612 case lltok::kw_sext:
2613 case lltok::kw_fptrunc:
2614 case lltok::kw_fpext:
2615 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002616 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002617 case lltok::kw_uitofp:
2618 case lltok::kw_sitofp:
2619 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002620 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002621 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002622 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002623 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002624 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002625 Constant *SrcVal;
2626 Lex.Lex();
2627 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2628 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002629 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002630 ParseType(DestTy) ||
2631 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2632 return true;
2633 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2634 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002635 getTypeString(SrcVal->getType()) + "' to '" +
2636 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002637 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002638 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002639 ID.Kind = ValID::t_Constant;
2640 return false;
2641 }
2642 case lltok::kw_extractvalue: {
2643 Lex.Lex();
2644 Constant *Val;
2645 SmallVector<unsigned, 4> Indices;
2646 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2647 ParseGlobalTypeAndValue(Val) ||
2648 ParseIndexList(Indices) ||
2649 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2650 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002651
Chris Lattner392be582010-02-12 20:49:41 +00002652 if (!Val->getType()->isAggregateType())
2653 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002654 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002655 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002656 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002657 ID.Kind = ValID::t_Constant;
2658 return false;
2659 }
2660 case lltok::kw_insertvalue: {
2661 Lex.Lex();
2662 Constant *Val0, *Val1;
2663 SmallVector<unsigned, 4> Indices;
2664 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2665 ParseGlobalTypeAndValue(Val0) ||
2666 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2667 ParseGlobalTypeAndValue(Val1) ||
2668 ParseIndexList(Indices) ||
2669 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2670 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002671 if (!Val0->getType()->isAggregateType())
2672 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002673 Type *IndexedType =
2674 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2675 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002676 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00002677 if (IndexedType != Val1->getType())
2678 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2679 getTypeString(Val1->getType()) +
2680 "' instead of '" + getTypeString(IndexedType) +
2681 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00002682 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002683 ID.Kind = ValID::t_Constant;
2684 return false;
2685 }
2686 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002687 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002688 unsigned PredVal, Opc = Lex.getUIntVal();
2689 Constant *Val0, *Val1;
2690 Lex.Lex();
2691 if (ParseCmpPredicate(PredVal, Opc) ||
2692 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2693 ParseGlobalTypeAndValue(Val0) ||
2694 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2695 ParseGlobalTypeAndValue(Val1) ||
2696 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2697 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002698
Chris Lattnerac161bf2009-01-02 07:01:27 +00002699 if (Val0->getType() != Val1->getType())
2700 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002701
Chris Lattnerac161bf2009-01-02 07:01:27 +00002702 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002703
Chris Lattnerac161bf2009-01-02 07:01:27 +00002704 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002705 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002706 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002707 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002708 } else {
2709 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002710 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002711 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002712 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002713 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002714 }
2715 ID.Kind = ValID::t_Constant;
2716 return false;
2717 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002718
Chris Lattnerac161bf2009-01-02 07:01:27 +00002719 // Binary Operators.
2720 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00002721 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002722 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002723 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002724 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00002725 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002726 case lltok::kw_udiv:
2727 case lltok::kw_sdiv:
2728 case lltok::kw_fdiv:
2729 case lltok::kw_urem:
2730 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002731 case lltok::kw_frem:
2732 case lltok::kw_shl:
2733 case lltok::kw_lshr:
2734 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002735 bool NUW = false;
2736 bool NSW = false;
2737 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002738 unsigned Opc = Lex.getUIntVal();
2739 Constant *Val0, *Val1;
2740 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00002741 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00002742 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2743 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002744 if (EatIfPresent(lltok::kw_nuw))
2745 NUW = true;
2746 if (EatIfPresent(lltok::kw_nsw)) {
2747 NSW = true;
2748 if (EatIfPresent(lltok::kw_nuw))
2749 NUW = true;
2750 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00002751 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2752 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002753 if (EatIfPresent(lltok::kw_exact))
2754 Exact = true;
2755 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002756 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2757 ParseGlobalTypeAndValue(Val0) ||
2758 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2759 ParseGlobalTypeAndValue(Val1) ||
2760 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2761 return true;
2762 if (Val0->getType() != Val1->getType())
2763 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002764 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00002765 if (NUW)
2766 return Error(ModifierLoc, "nuw only applies to integer operations");
2767 if (NSW)
2768 return Error(ModifierLoc, "nsw only applies to integer operations");
2769 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00002770 // Check that the type is valid for the operator.
2771 switch (Opc) {
2772 case Instruction::Add:
2773 case Instruction::Sub:
2774 case Instruction::Mul:
2775 case Instruction::UDiv:
2776 case Instruction::SDiv:
2777 case Instruction::URem:
2778 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00002779 case Instruction::Shl:
2780 case Instruction::AShr:
2781 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00002782 if (!Val0->getType()->isIntOrIntVectorTy())
2783 return Error(ID.Loc, "constexpr requires integer operands");
2784 break;
2785 case Instruction::FAdd:
2786 case Instruction::FSub:
2787 case Instruction::FMul:
2788 case Instruction::FDiv:
2789 case Instruction::FRem:
2790 if (!Val0->getType()->isFPOrFPVectorTy())
2791 return Error(ID.Loc, "constexpr requires fp operands");
2792 break;
2793 default: llvm_unreachable("Unknown binary operator!");
2794 }
Dan Gohman1b849082009-09-07 23:54:19 +00002795 unsigned Flags = 0;
2796 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2797 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002798 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00002799 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00002800 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002801 ID.Kind = ValID::t_Constant;
2802 return false;
2803 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002804
Chris Lattnerac161bf2009-01-02 07:01:27 +00002805 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00002806 case lltok::kw_and:
2807 case lltok::kw_or:
2808 case lltok::kw_xor: {
2809 unsigned Opc = Lex.getUIntVal();
2810 Constant *Val0, *Val1;
2811 Lex.Lex();
2812 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2813 ParseGlobalTypeAndValue(Val0) ||
2814 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2815 ParseGlobalTypeAndValue(Val1) ||
2816 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2817 return true;
2818 if (Val0->getType() != Val1->getType())
2819 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002820 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002821 return Error(ID.Loc,
2822 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002823 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002824 ID.Kind = ValID::t_Constant;
2825 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002826 }
2827
Chris Lattnerac161bf2009-01-02 07:01:27 +00002828 case lltok::kw_getelementptr:
2829 case lltok::kw_shufflevector:
2830 case lltok::kw_insertelement:
2831 case lltok::kw_extractelement:
2832 case lltok::kw_select: {
2833 unsigned Opc = Lex.getUIntVal();
2834 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00002835 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00002836 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002837 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00002838
Dan Gohman1639c392009-07-27 21:53:46 +00002839 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00002840 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00002841
2842 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2843 return true;
2844
2845 LocTy ExplicitTypeLoc = Lex.getLoc();
2846 if (Opc == Instruction::GetElementPtr) {
2847 if (ParseType(Ty) ||
2848 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2849 return true;
2850 }
2851
2852 if (ParseGlobalValueVector(Elts) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002853 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2854 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002855
Chris Lattnerac161bf2009-01-02 07:01:27 +00002856 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00002857 if (Elts.size() == 0 ||
2858 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00002859 return Error(ID.Loc, "base of getelementptr must be a pointer");
2860
2861 Type *BaseType = Elts[0]->getType();
2862 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00002863 if (Ty != BasePointerType->getElementType())
2864 return Error(
2865 ExplicitTypeLoc,
2866 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002867
Jay Foaded8db7d2011-07-21 14:31:17 +00002868 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00002869 for (Constant *Val : Indices) {
2870 Type *ValTy = Val->getType();
2871 if (!ValTy->getScalarType()->isIntegerTy())
2872 return Error(ID.Loc, "getelementptr index must be an integer");
2873 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2874 return Error(ID.Loc, "getelementptr index type missmatch");
2875 if (ValTy->isVectorTy()) {
2876 unsigned ValNumEl = cast<VectorType>(ValTy)->getNumElements();
2877 unsigned PtrNumEl = cast<VectorType>(BaseType)->getNumElements();
2878 if (ValNumEl != PtrNumEl)
2879 return Error(
2880 ID.Loc,
2881 "getelementptr vector index has a wrong number of elements");
2882 }
2883 }
2884
Owen Andersone90f9922015-03-10 06:34:57 +00002885 SmallPtrSet<const Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00002886 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00002887 return Error(ID.Loc, "base element of getelementptr must be sized");
2888
David Blaikie4a2e73b2015-04-02 18:55:32 +00002889 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00002890 return Error(ID.Loc, "invalid getelementptr indices");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002891 ID.ConstantVal =
2892 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002893 } else if (Opc == Instruction::Select) {
2894 if (Elts.size() != 3)
2895 return Error(ID.Loc, "expected three operands to select");
2896 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2897 Elts[2]))
2898 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00002899 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002900 } else if (Opc == Instruction::ShuffleVector) {
2901 if (Elts.size() != 3)
2902 return Error(ID.Loc, "expected three operands to shufflevector");
2903 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2904 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00002905 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002906 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002907 } else if (Opc == Instruction::ExtractElement) {
2908 if (Elts.size() != 2)
2909 return Error(ID.Loc, "expected two operands to extractelement");
2910 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2911 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00002912 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002913 } else {
2914 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2915 if (Elts.size() != 3)
2916 return Error(ID.Loc, "expected three operands to insertelement");
2917 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2918 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00002919 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00002920 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002921 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002922
Chris Lattnerac161bf2009-01-02 07:01:27 +00002923 ID.Kind = ValID::t_Constant;
2924 return false;
2925 }
2926 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002927
Chris Lattnerac161bf2009-01-02 07:01:27 +00002928 Lex.Lex();
2929 return false;
2930}
2931
2932/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00002933bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002934 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002935 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00002936 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00002937 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00002938 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002939 if (V && !(C = dyn_cast<Constant>(V)))
2940 return Error(ID.Loc, "global values must be constants");
2941 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002942}
2943
Victor Hernandez9d75c962010-01-11 22:31:58 +00002944bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002945 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002946 return ParseType(Ty) ||
2947 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00002948}
2949
Rafael Espindola83a362c2015-01-06 22:55:16 +00002950bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00002951 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002952
2953 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00002954 if (!EatIfPresent(lltok::kw_comdat))
2955 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00002956
2957 if (EatIfPresent(lltok::lparen)) {
2958 if (Lex.getKind() != lltok::ComdatVar)
2959 return TokError("expected comdat variable");
2960 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2961 Lex.Lex();
2962 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2963 return true;
2964 } else {
2965 if (GlobalName.empty())
2966 return TokError("comdat cannot be unnamed");
2967 C = getComdat(GlobalName, KwLoc);
2968 }
2969
David Majnemerdad0a642014-06-27 18:19:56 +00002970 return false;
2971}
2972
Victor Hernandez9d75c962010-01-11 22:31:58 +00002973/// ParseGlobalValueVector
2974/// ::= /*empty*/
2975/// ::= TypeAndValue (',' TypeAndValue)*
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002976bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00002977 // Empty list.
2978 if (Lex.getKind() == lltok::rbrace ||
2979 Lex.getKind() == lltok::rsquare ||
2980 Lex.getKind() == lltok::greater ||
2981 Lex.getKind() == lltok::rparen)
2982 return false;
2983
2984 Constant *C;
2985 if (ParseGlobalTypeAndValue(C)) return true;
2986 Elts.push_back(C);
2987
2988 while (EatIfPresent(lltok::comma)) {
2989 if (ParseGlobalTypeAndValue(C)) return true;
2990 Elts.push_back(C);
2991 }
2992
2993 return false;
2994}
2995
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00002996bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002997 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002998 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00002999 return true;
3000
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003001 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003002 return false;
3003}
3004
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003005/// MDNode:
3006/// ::= !{ ... }
3007/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003008/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003009bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003010 if (Lex.getKind() == lltok::MetadataVar)
3011 return ParseSpecializedMDNode(N);
3012
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003013 return ParseToken(lltok::exclaim, "expected '!' here") ||
3014 ParseMDNodeTail(N);
3015}
3016
3017bool LLParser::ParseMDNodeTail(MDNode *&N) {
3018 // !{ ... }
3019 if (Lex.getKind() == lltok::lbrace)
3020 return ParseMDTuple(N);
3021
3022 // !42
3023 return ParseMDNodeID(N);
3024}
3025
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003026namespace {
3027
3028/// Structure to represent an optional metadata field.
3029template <class FieldTy> struct MDFieldImpl {
3030 typedef MDFieldImpl ImplTy;
3031 FieldTy Val;
3032 bool Seen;
3033
3034 void assign(FieldTy Val) {
3035 Seen = true;
3036 this->Val = std::move(Val);
3037 }
3038
3039 explicit MDFieldImpl(FieldTy Default)
3040 : Val(std::move(Default)), Seen(false) {}
3041};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003042
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003043struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3044 uint64_t Max;
3045
3046 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3047 : ImplTy(Default), Max(Max) {}
3048};
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003049struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003050 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003051};
3052struct ColumnField : public MDUnsignedField {
3053 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3054};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003055struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003056 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003057 DwarfTagField(dwarf::Tag DefaultTag)
3058 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003059};
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003060struct DwarfAttEncodingField : public MDUnsignedField {
3061 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3062};
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003063struct DwarfVirtualityField : public MDUnsignedField {
3064 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3065};
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003066struct DwarfLangField : public MDUnsignedField {
3067 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3068};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003069
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003070struct DIFlagField : public MDUnsignedField {
3071 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3072};
3073
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003074struct MDSignedField : public MDFieldImpl<int64_t> {
3075 int64_t Min;
3076 int64_t Max;
3077
3078 MDSignedField(int64_t Default = 0)
3079 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3080 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3081 : ImplTy(Default), Min(Min), Max(Max) {}
3082};
3083
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003084struct MDBoolField : public MDFieldImpl<bool> {
3085 MDBoolField(bool Default = false) : ImplTy(Default) {}
3086};
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003087struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003088 bool AllowNull;
3089
3090 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003091};
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003092struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3093 MDConstant() : ImplTy(nullptr) {}
3094};
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003095struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003096 bool AllowEmpty;
3097 MDStringField(bool AllowEmpty = true)
3098 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003099};
3100struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3101 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3102};
3103
3104} // end namespace
3105
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003106namespace llvm {
3107
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003108template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003109bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003110 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003111 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3112 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003113
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003114 auto &U = Lex.getAPSIntVal();
3115 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003116 return TokError("value for '" + Name + "' too large, limit is " +
3117 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003118 Result.assign(U.getZExtValue());
3119 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003120 Lex.Lex();
3121 return false;
3122}
3123
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003124template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003125bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3126 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3127}
3128template <>
3129bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3130 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3131}
3132
3133template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003134bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3135 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003136 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003137
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003138 if (Lex.getKind() != lltok::DwarfTag)
3139 return TokError("expected DWARF tag");
3140
3141 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3142 if (Tag == dwarf::DW_TAG_invalid)
3143 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003144 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003145
3146 Result.assign(Tag);
3147 Lex.Lex();
3148 return false;
3149}
3150
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003151template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003152bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3153 DwarfVirtualityField &Result) {
3154 if (Lex.getKind() == lltok::APSInt)
3155 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3156
3157 if (Lex.getKind() != lltok::DwarfVirtuality)
3158 return TokError("expected DWARF virtuality code");
3159
3160 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3161 if (!Virtuality)
3162 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3163 Lex.getStrVal() + "'");
3164 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3165 Result.assign(Virtuality);
3166 Lex.Lex();
3167 return false;
3168}
3169
3170template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003171bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3172 if (Lex.getKind() == lltok::APSInt)
3173 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3174
3175 if (Lex.getKind() != lltok::DwarfLang)
3176 return TokError("expected DWARF language");
3177
3178 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3179 if (!Lang)
3180 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3181 "'");
3182 assert(Lang <= Result.Max && "Expected valid DWARF language");
3183 Result.assign(Lang);
3184 Lex.Lex();
3185 return false;
3186}
3187
3188template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003189bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003190 DwarfAttEncodingField &Result) {
3191 if (Lex.getKind() == lltok::APSInt)
3192 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3193
3194 if (Lex.getKind() != lltok::DwarfAttEncoding)
3195 return TokError("expected DWARF type attribute encoding");
3196
3197 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3198 if (!Encoding)
3199 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3200 Lex.getStrVal() + "'");
3201 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3202 Result.assign(Encoding);
3203 Lex.Lex();
3204 return false;
3205}
3206
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003207/// DIFlagField
3208/// ::= uint32
3209/// ::= DIFlagVector
3210/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3211template <>
3212bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3213 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3214
3215 // Parser for a single flag.
3216 auto parseFlag = [&](unsigned &Val) {
3217 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3218 return ParseUInt32(Val);
3219
3220 if (Lex.getKind() != lltok::DIFlag)
3221 return TokError("expected debug info flag");
3222
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003223 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003224 if (!Val)
3225 return TokError(Twine("invalid debug info flag flag '") +
3226 Lex.getStrVal() + "'");
3227 Lex.Lex();
3228 return false;
3229 };
3230
3231 // Parse the flags and combine them together.
3232 unsigned Combined = 0;
3233 do {
3234 unsigned Val;
3235 if (parseFlag(Val))
3236 return true;
3237 Combined |= Val;
3238 } while (EatIfPresent(lltok::bar));
3239
3240 Result.assign(Combined);
3241 return false;
3242}
3243
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003244template <>
3245bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003246 MDSignedField &Result) {
3247 if (Lex.getKind() != lltok::APSInt)
3248 return TokError("expected signed integer");
3249
3250 auto &S = Lex.getAPSIntVal();
3251 if (S < Result.Min)
3252 return TokError("value for '" + Name + "' too small, limit is " +
3253 Twine(Result.Min));
3254 if (S > Result.Max)
3255 return TokError("value for '" + Name + "' too large, limit is " +
3256 Twine(Result.Max));
3257 Result.assign(S.getExtValue());
3258 assert(Result.Val >= Result.Min && "Expected value in range");
3259 assert(Result.Val <= Result.Max && "Expected value in range");
3260 Lex.Lex();
3261 return false;
3262}
3263
3264template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003265bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3266 switch (Lex.getKind()) {
3267 default:
3268 return TokError("expected 'true' or 'false'");
3269 case lltok::kw_true:
3270 Result.assign(true);
3271 break;
3272 case lltok::kw_false:
3273 Result.assign(false);
3274 break;
3275 }
3276 Lex.Lex();
3277 return false;
3278}
3279
3280template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003281bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003282 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003283 if (!Result.AllowNull)
3284 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003285 Lex.Lex();
3286 Result.assign(nullptr);
3287 return false;
3288 }
3289
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003290 Metadata *MD;
3291 if (ParseMetadata(MD, nullptr))
3292 return true;
3293
3294 Result.assign(MD);
3295 return false;
3296}
3297
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003298template <>
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003299bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3300 Metadata *MD;
3301 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3302 return true;
3303
3304 Result.assign(cast<ConstantAsMetadata>(MD));
3305 return false;
3306}
3307
3308template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003309bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003310 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003311 std::string S;
3312 if (ParseStringConstant(S))
3313 return true;
3314
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003315 if (!Result.AllowEmpty && S.empty())
3316 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3317
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003318 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003319 return false;
3320}
3321
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003322template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003323bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3324 SmallVector<Metadata *, 4> MDs;
3325 if (ParseMDNodeVector(MDs))
3326 return true;
3327
3328 Result.assign(std::move(MDs));
3329 return false;
3330}
3331
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003332} // end namespace llvm
3333
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003334template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003335bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003336 do {
3337 if (Lex.getKind() != lltok::LabelStr)
3338 return TokError("expected field label here");
3339
3340 if (parseField())
3341 return true;
3342 } while (EatIfPresent(lltok::comma));
3343
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003344 return false;
3345}
3346
3347template <class ParserTy>
3348bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3349 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3350 Lex.Lex();
3351
3352 if (ParseToken(lltok::lparen, "expected '(' here"))
3353 return true;
3354 if (Lex.getKind() != lltok::rparen)
3355 if (ParseMDFieldsImplBody(parseField))
3356 return true;
3357
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003358 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003359 return ParseToken(lltok::rparen, "expected ')' here");
3360}
3361
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003362template <class FieldTy>
3363bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3364 if (Result.Seen)
3365 return TokError("field '" + Name + "' cannot be specified more than once");
3366
3367 LocTy Loc = Lex.getLoc();
3368 Lex.Lex();
3369 return ParseMDField(Loc, Name, Result);
3370}
3371
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003372bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3373 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003374
3375#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003376 if (Lex.getStrVal() == #CLASS) \
3377 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003378#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003379
3380 return TokError("expected metadata type");
3381}
3382
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003383#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3384#define NOP_FIELD(NAME, TYPE, INIT)
3385#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3386 if (!NAME.Seen) \
3387 return Error(ClosingLoc, "missing required field '" #NAME "'");
3388#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003389 if (Lex.getStrVal() == #NAME) \
3390 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003391#define PARSE_MD_FIELDS() \
3392 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3393 do { \
3394 LocTy ClosingLoc; \
3395 if (ParseMDFieldsImpl([&]() -> bool { \
3396 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3397 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3398 }, ClosingLoc)) \
3399 return true; \
3400 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3401 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003402#define GET_OR_DISTINCT(CLASS, ARGS) \
3403 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003404
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003405/// ParseDILocationFields:
3406/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3407bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003408#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003409 OPTIONAL(line, LineField, ); \
3410 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003411 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003412 OPTIONAL(inlinedAt, MDField, );
3413 PARSE_MD_FIELDS();
3414#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003415
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003416 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003417 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003418 return false;
3419}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003420
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003421/// ParseGenericDINode:
3422/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3423bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003424#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003425 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003426 OPTIONAL(header, MDStringField, ); \
3427 OPTIONAL(operands, MDFieldList, );
3428 PARSE_MD_FIELDS();
3429#undef VISIT_MD_FIELDS
3430
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003431 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003432 (Context, tag.Val, header.Val, operands.Val));
3433 return false;
3434}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003435
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003436/// ParseDISubrange:
3437/// ::= !DISubrange(count: 30, lowerBound: 2)
3438bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003439#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003440 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003441 OPTIONAL(lowerBound, MDSignedField, );
3442 PARSE_MD_FIELDS();
3443#undef VISIT_MD_FIELDS
3444
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003445 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003446 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003447}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003448
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003449/// ParseDIEnumerator:
3450/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3451bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003452#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003453 REQUIRED(name, MDStringField, ); \
3454 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003455 PARSE_MD_FIELDS();
3456#undef VISIT_MD_FIELDS
3457
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003458 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003459 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003460}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003461
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003462/// ParseDIBasicType:
3463/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3464bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003465#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003466 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003467 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003468 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3469 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003470 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003471 PARSE_MD_FIELDS();
3472#undef VISIT_MD_FIELDS
3473
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003474 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003475 align.Val, encoding.Val));
3476 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003477}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003478
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003479/// ParseDIDerivedType:
3480/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003481/// line: 7, scope: !1, baseType: !2, size: 32,
3482/// align: 32, offset: 0, flags: 0, extraData: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003483bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003484#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3485 REQUIRED(tag, DwarfTagField, ); \
3486 OPTIONAL(name, MDStringField, ); \
3487 OPTIONAL(file, MDField, ); \
3488 OPTIONAL(line, LineField, ); \
3489 OPTIONAL(scope, MDField, ); \
3490 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003491 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3492 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3493 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003494 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003495 OPTIONAL(extraData, MDField, );
3496 PARSE_MD_FIELDS();
3497#undef VISIT_MD_FIELDS
3498
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003499 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003500 (Context, tag.Val, name.Val, file.Val, line.Val,
3501 scope.Val, baseType.Val, size.Val, align.Val,
3502 offset.Val, flags.Val, extraData.Val));
3503 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003504}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003505
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003506bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003507#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3508 REQUIRED(tag, DwarfTagField, ); \
3509 OPTIONAL(name, MDStringField, ); \
3510 OPTIONAL(file, MDField, ); \
3511 OPTIONAL(line, LineField, ); \
3512 OPTIONAL(scope, MDField, ); \
3513 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003514 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3515 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3516 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003517 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003518 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003519 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003520 OPTIONAL(vtableHolder, MDField, ); \
3521 OPTIONAL(templateParams, MDField, ); \
3522 OPTIONAL(identifier, MDStringField, );
3523 PARSE_MD_FIELDS();
3524#undef VISIT_MD_FIELDS
3525
3526 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003527 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003528 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3529 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3530 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3531 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003532}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003533
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003534bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003535#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003536 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003537 REQUIRED(types, MDField, );
3538 PARSE_MD_FIELDS();
3539#undef VISIT_MD_FIELDS
3540
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003541 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003542 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003543}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003544
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003545/// ParseDIFileType:
3546/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3547bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003548#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3549 REQUIRED(filename, MDStringField, ); \
3550 REQUIRED(directory, MDStringField, );
3551 PARSE_MD_FIELDS();
3552#undef VISIT_MD_FIELDS
3553
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003554 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003555 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003556}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003557
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003558/// ParseDICompileUnit:
3559/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003560/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3561/// splitDebugFilename: "abc.debug", emissionKind: 1,
3562/// enums: !1, retainedTypes: !2, subprograms: !3,
Adrian Prantl1f599f92015-05-21 20:37:30 +00003563/// globals: !4, imports: !5, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003564bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003565#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3566 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00003567 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003568 OPTIONAL(producer, MDStringField, ); \
3569 OPTIONAL(isOptimized, MDBoolField, ); \
3570 OPTIONAL(flags, MDStringField, ); \
3571 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3572 OPTIONAL(splitDebugFilename, MDStringField, ); \
3573 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3574 OPTIONAL(enums, MDField, ); \
3575 OPTIONAL(retainedTypes, MDField, ); \
3576 OPTIONAL(subprograms, MDField, ); \
3577 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00003578 OPTIONAL(imports, MDField, ); \
3579 OPTIONAL(dwoId, MDUnsignedField, );
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003580 PARSE_MD_FIELDS();
3581#undef VISIT_MD_FIELDS
3582
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003583 Result = GET_OR_DISTINCT(DICompileUnit,
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003584 (Context, language.Val, file.Val, producer.Val,
3585 isOptimized.Val, flags.Val, runtimeVersion.Val,
3586 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3587 retainedTypes.Val, subprograms.Val, globals.Val,
Adrian Prantl1f599f92015-05-21 20:37:30 +00003588 imports.Val, dwoId.Val));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003589 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003590}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00003591
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003592/// ParseDISubprogram:
3593/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003594/// file: !1, line: 7, type: !2, isLocal: false,
3595/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003596/// virtuality: DW_VIRTUALTIY_pure_virtual,
3597/// virtualIndex: 10, flags: 11,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003598/// isOptimized: false, function: void ()* @_Z3foov,
3599/// templateParams: !4, declaration: !5, variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003600bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003601#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3602 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003603 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003604 OPTIONAL(linkageName, MDStringField, ); \
3605 OPTIONAL(file, MDField, ); \
3606 OPTIONAL(line, LineField, ); \
3607 OPTIONAL(type, MDField, ); \
3608 OPTIONAL(isLocal, MDBoolField, ); \
3609 OPTIONAL(isDefinition, MDBoolField, (true)); \
3610 OPTIONAL(scopeLine, LineField, ); \
3611 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003612 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003613 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003614 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003615 OPTIONAL(isOptimized, MDBoolField, ); \
3616 OPTIONAL(function, MDConstant, ); \
3617 OPTIONAL(templateParams, MDField, ); \
3618 OPTIONAL(declaration, MDField, ); \
3619 OPTIONAL(variables, MDField, );
3620 PARSE_MD_FIELDS();
3621#undef VISIT_MD_FIELDS
3622
3623 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003624 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003625 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3626 scopeLine.Val, containingType.Val, virtuality.Val,
3627 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3628 templateParams.Val, declaration.Val, variables.Val));
3629 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003630}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003631
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003632/// ParseDILexicalBlock:
3633/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3634bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003635#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003636 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003637 OPTIONAL(file, MDField, ); \
3638 OPTIONAL(line, LineField, ); \
3639 OPTIONAL(column, ColumnField, );
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 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003645 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003646}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00003647
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003648/// ParseDILexicalBlockFile:
3649/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3650bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003651#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00003652 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003653 OPTIONAL(file, MDField, ); \
3654 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3655 PARSE_MD_FIELDS();
3656#undef VISIT_MD_FIELDS
3657
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003658 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003659 (Context, scope.Val, file.Val, discriminator.Val));
3660 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003661}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00003662
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003663/// ParseDINamespace:
3664/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3665bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003666#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3667 REQUIRED(scope, MDField, ); \
3668 OPTIONAL(file, MDField, ); \
3669 OPTIONAL(name, MDStringField, ); \
3670 OPTIONAL(line, LineField, );
3671 PARSE_MD_FIELDS();
3672#undef VISIT_MD_FIELDS
3673
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003674 Result = GET_OR_DISTINCT(DINamespace,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003675 (Context, scope.Val, file.Val, name.Val, line.Val));
3676 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003677}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00003678
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003679/// ParseDITemplateTypeParameter:
3680/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3681bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003682#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003683 OPTIONAL(name, MDStringField, ); \
3684 REQUIRED(type, MDField, );
3685 PARSE_MD_FIELDS();
3686#undef VISIT_MD_FIELDS
3687
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003688 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003689 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003690 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003691}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003692
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003693/// ParseDITemplateValueParameter:
3694/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003695/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003696bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003697#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003698 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003699 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003700 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003701 REQUIRED(value, MDField, );
3702 PARSE_MD_FIELDS();
3703#undef VISIT_MD_FIELDS
3704
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003705 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003706 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003707 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003708}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003709
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003710/// ParseDIGlobalVariable:
3711/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003712/// file: !1, line: 7, type: !2, isLocal: false,
3713/// isDefinition: true, variable: i32* @foo,
3714/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003715bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003716#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003717 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003718 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003719 OPTIONAL(linkageName, MDStringField, ); \
3720 OPTIONAL(file, MDField, ); \
3721 OPTIONAL(line, LineField, ); \
3722 OPTIONAL(type, MDField, ); \
3723 OPTIONAL(isLocal, MDBoolField, ); \
3724 OPTIONAL(isDefinition, MDBoolField, (true)); \
3725 OPTIONAL(variable, MDConstant, ); \
3726 OPTIONAL(declaration, MDField, );
3727 PARSE_MD_FIELDS();
3728#undef VISIT_MD_FIELDS
3729
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003730 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003731 (Context, scope.Val, name.Val, linkageName.Val,
3732 file.Val, line.Val, type.Val, isLocal.Val,
3733 isDefinition.Val, variable.Val, declaration.Val));
3734 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003735}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003736
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003737/// ParseDILocalVariable:
3738/// ::= !DILocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003739/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003740bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003741#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3742 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003743 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003744 OPTIONAL(name, MDStringField, ); \
3745 OPTIONAL(file, MDField, ); \
3746 OPTIONAL(line, LineField, ); \
3747 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith69488692015-06-02 17:17:44 +00003748 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003749 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003750 PARSE_MD_FIELDS();
3751#undef VISIT_MD_FIELDS
3752
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003753 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003754 (Context, tag.Val, scope.Val, name.Val, file.Val,
3755 line.Val, type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003756 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003757}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003758
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003759/// ParseDIExpression:
3760/// ::= !DIExpression(0, 7, -1)
3761bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003762 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3763 Lex.Lex();
3764
3765 if (ParseToken(lltok::lparen, "expected '(' here"))
3766 return true;
3767
3768 SmallVector<uint64_t, 8> Elements;
3769 if (Lex.getKind() != lltok::rparen)
3770 do {
3771 if (Lex.getKind() == lltok::DwarfOp) {
3772 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3773 Lex.Lex();
3774 Elements.push_back(Op);
3775 continue;
3776 }
3777 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3778 }
3779
3780 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3781 return TokError("expected unsigned integer");
3782
3783 auto &U = Lex.getAPSIntVal();
3784 if (U.ugt(UINT64_MAX))
3785 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3786 Elements.push_back(U.getZExtValue());
3787 Lex.Lex();
3788 } while (EatIfPresent(lltok::comma));
3789
3790 if (ParseToken(lltok::rparen, "expected ')' here"))
3791 return true;
3792
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003793 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003794 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003795}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003796
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003797/// ParseDIObjCProperty:
3798/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003799/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003800bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003801#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003802 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003803 OPTIONAL(file, MDField, ); \
3804 OPTIONAL(line, LineField, ); \
3805 OPTIONAL(setter, MDStringField, ); \
3806 OPTIONAL(getter, MDStringField, ); \
3807 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3808 OPTIONAL(type, MDField, );
3809 PARSE_MD_FIELDS();
3810#undef VISIT_MD_FIELDS
3811
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003812 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003813 (Context, name.Val, file.Val, line.Val, setter.Val,
3814 getter.Val, attributes.Val, type.Val));
3815 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003816}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003817
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003818/// ParseDIImportedEntity:
3819/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003820/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003821bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003822#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3823 REQUIRED(tag, DwarfTagField, ); \
3824 REQUIRED(scope, MDField, ); \
3825 OPTIONAL(entity, MDField, ); \
3826 OPTIONAL(line, LineField, ); \
3827 OPTIONAL(name, MDStringField, );
3828 PARSE_MD_FIELDS();
3829#undef VISIT_MD_FIELDS
3830
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003831 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003832 entity.Val, line.Val, name.Val));
3833 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003834}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003835
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003836#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003837#undef NOP_FIELD
3838#undef REQUIRE_FIELD
3839#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003840
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003841/// ParseMetadataAsValue
3842/// ::= metadata i32 %local
3843/// ::= metadata i32 @global
3844/// ::= metadata i32 7
3845/// ::= metadata !0
3846/// ::= metadata !{...}
3847/// ::= metadata !"string"
3848bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3849 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003850 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003851 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003852 return true;
3853
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003854 V = MetadataAsValue::get(Context, MD);
3855 return false;
3856}
3857
3858/// ParseValueAsMetadata
3859/// ::= i32 %local
3860/// ::= i32 @global
3861/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003862bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3863 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003864 Type *Ty;
3865 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003866 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003867 return true;
3868 if (Ty->isMetadataTy())
3869 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3870
3871 Value *V;
3872 if (ParseValue(Ty, V, PFS))
3873 return true;
3874
3875 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003876 return false;
3877}
3878
3879/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003880/// ::= i32 %local
3881/// ::= i32 @global
3882/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00003883/// ::= !42
3884/// ::= !{...}
3885/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003886/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003887bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003888 if (Lex.getKind() == lltok::MetadataVar) {
3889 MDNode *N;
3890 if (ParseSpecializedMDNode(N))
3891 return true;
3892 MD = N;
3893 return false;
3894 }
3895
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003896 // ValueAsMetadata:
3897 // <type> <value>
3898 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003899 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003900
3901 // '!'.
3902 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3903 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00003904
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003905 // MDString:
3906 // ::= '!' STRINGCONSTANT
3907 if (Lex.getKind() == lltok::StringConstant) {
3908 MDString *S;
3909 if (ParseMDString(S))
3910 return true;
3911 MD = S;
3912 return false;
3913 }
3914
Dan Gohman8939ba332010-07-14 18:26:50 +00003915 // MDNode:
3916 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003917 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003918 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003919 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003920 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003921 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003922 return false;
3923}
3924
Victor Hernandez9d75c962010-01-11 22:31:58 +00003925
3926//===----------------------------------------------------------------------===//
3927// Function Parsing.
3928//===----------------------------------------------------------------------===//
3929
Chris Lattner229907c2011-07-18 04:54:35 +00003930bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003931 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003932 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003933 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003934
Chris Lattnerac161bf2009-01-02 07:01:27 +00003935 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003936 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003937 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3938 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003939 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003940 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003941 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3942 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003943 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003944 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003945 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003946 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003947 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003948 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3949 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003950 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003951 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003952 return false;
3953 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003954 case ValID::t_GlobalName:
3955 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003956 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003957 case ValID::t_GlobalID:
3958 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003959 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003960 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003961 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003962 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003963 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003964 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003965 return false;
3966 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003967 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003968 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3969 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003970
Dan Gohman518cda42011-12-17 00:04:22 +00003971 // The lexer has no type info, so builds all half, float, and double FP
3972 // constants as double. Fix this here. Long double does not need this.
3973 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003974 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003975 if (Ty->isHalfTy())
3976 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3977 &Ignored);
3978 else if (Ty->isFloatTy())
3979 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3980 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003981 }
Owen Anderson69c464d2009-07-27 20:59:43 +00003982 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003983
Chris Lattner8f57d29e2009-01-05 18:24:23 +00003984 if (V->getType() != Ty)
3985 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00003986 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003987
Chris Lattnerac161bf2009-01-02 07:01:27 +00003988 return false;
3989 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00003990 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003991 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003992 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00003993 return false;
3994 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00003995 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003996 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00003997 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00003998 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003999 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004000 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004001 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004002 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004003 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004004 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004005 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004006 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004007 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004008 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004009 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004010 return false;
4011 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004012 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004013 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004014
Chris Lattnerac161bf2009-01-02 07:01:27 +00004015 V = ID.ConstantVal;
4016 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004017 case ValID::t_ConstantStruct:
4018 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004019 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004020 if (ST->getNumElements() != ID.UIntVal)
4021 return Error(ID.Loc,
4022 "initializer with struct type has wrong # elements");
4023 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4024 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004025
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004026 // Verify that the elements are compatible with the structtype.
4027 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4028 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4029 return Error(ID.Loc, "element " + Twine(i) +
4030 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004031
Reid Kleckner2ae03e12015-03-04 18:31:10 +00004032 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4033 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004034 } else
4035 return Error(ID.Loc, "constant expression type mismatch");
4036 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004037 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004038 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004039}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004040
Chris Lattner229907c2011-07-18 04:54:35 +00004041bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004042 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004043 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004044 return ParseValID(ID, PFS) ||
4045 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004046}
4047
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004048bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004049 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004050 return ParseType(Ty) ||
4051 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004052}
4053
Chris Lattner3ed871f2009-10-27 19:13:16 +00004054bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4055 PerFunctionState &PFS) {
4056 Value *V;
4057 Loc = Lex.getLoc();
4058 if (ParseTypeAndValue(V, PFS)) return true;
4059 if (!isa<BasicBlock>(V))
4060 return Error(Loc, "expected a basic block");
4061 BB = cast<BasicBlock>(V);
4062 return false;
4063}
4064
4065
Chris Lattnerac161bf2009-01-02 07:01:27 +00004066/// FunctionHeader
4067/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004068/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004069/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004070bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4071 // Parse the linkage.
4072 LocTy LinkageLoc = Lex.getLoc();
4073 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004074
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004075 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004076 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004077 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004078 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004079 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004080 LocTy RetTypeLoc = Lex.getLoc();
4081 if (ParseOptionalLinkage(Linkage) ||
4082 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004083 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004084 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004085 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004086 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004087 return true;
4088
4089 // Verify that the linkage is ok.
4090 switch ((GlobalValue::LinkageTypes)Linkage) {
4091 case GlobalValue::ExternalLinkage:
4092 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004093 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004094 if (isDefine)
4095 return Error(LinkageLoc, "invalid linkage for function definition");
4096 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004097 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004098 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004099 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004100 case GlobalValue::LinkOnceAnyLinkage:
4101 case GlobalValue::LinkOnceODRLinkage:
4102 case GlobalValue::WeakAnyLinkage:
4103 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004104 if (!isDefine)
4105 return Error(LinkageLoc, "invalid linkage for function declaration");
4106 break;
4107 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004108 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004109 return Error(LinkageLoc, "invalid function linkage type");
4110 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004111
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004112 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4113 return Error(LinkageLoc,
4114 "symbol with local linkage must have default visibility");
4115
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004116 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004117 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004118
Chris Lattnerac161bf2009-01-02 07:01:27 +00004119 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004120
4121 std::string FunctionName;
4122 if (Lex.getKind() == lltok::GlobalVar) {
4123 FunctionName = Lex.getStrVal();
4124 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4125 unsigned NameID = Lex.getUIntVal();
4126
4127 if (NameID != NumberedVals.size())
4128 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004129 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004130 } else {
4131 return TokError("expected function name");
4132 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004133
Chris Lattner3822f632009-01-02 08:05:26 +00004134 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004135
Chris Lattner3822f632009-01-02 08:05:26 +00004136 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004137 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004138
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004139 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004140 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004141 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004142 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004143 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004144 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004145 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004146 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004147 bool UnnamedAddr;
4148 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004149 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004150 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004151 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004152 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004153
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004154 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004155 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4156 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004157 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004158 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004159 (EatIfPresent(lltok::kw_section) &&
4160 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004161 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004162 ParseOptionalAlignment(Alignment) ||
4163 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004164 ParseStringConstant(GC)) ||
4165 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004166 ParseGlobalTypeAndValue(Prefix)) ||
4167 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004168 ParseGlobalTypeAndValue(Prologue)) ||
4169 (EatIfPresent(lltok::kw_personality) &&
4170 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004171 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004172
Michael Gottesman41748d72013-06-27 00:25:01 +00004173 if (FuncAttrs.contains(Attribute::Builtin))
4174 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004175
Chris Lattnerac161bf2009-01-02 07:01:27 +00004176 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004177 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004178 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004179 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004180 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004181
Chris Lattnerac161bf2009-01-02 07:01:27 +00004182 // Okay, if we got here, the function is syntactically valid. Convert types
4183 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004184 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004185 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004186
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004187 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004188 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4189 AttributeSet::ReturnIndex,
4190 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004191
Chris Lattnerac161bf2009-01-02 07:01:27 +00004192 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004193 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004194 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4195 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004196 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4197 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004198 }
4199
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004200 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004201 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4202 AttributeSet::FunctionIndex,
4203 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004204
Bill Wendlinge94d8432012-12-07 23:16:57 +00004205 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004206
Bill Wendling749a43d2012-12-30 13:50:49 +00004207 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004208 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4209
Chris Lattner229907c2011-07-18 04:54:35 +00004210 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004211 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004212 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004213
Craig Topper2617dcc2014-04-15 06:32:26 +00004214 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004215 if (!FunctionName.empty()) {
4216 // If this was a definition of a forward reference, remove the definition
4217 // from the forward reference table and fill in the forward ref.
4218 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4219 ForwardRefVals.find(FunctionName);
4220 if (FRVI != ForwardRefVals.end()) {
4221 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004222 if (!Fn)
4223 return Error(FRVI->second.second, "invalid forward reference to "
4224 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004225 if (Fn->getType() != PFT)
4226 return Error(FRVI->second.second, "invalid forward reference to "
4227 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004228
Chris Lattnerac161bf2009-01-02 07:01:27 +00004229 ForwardRefVals.erase(FRVI);
4230 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004231 // Reject redefinitions.
4232 return Error(NameLoc, "invalid redefinition of function '" +
4233 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004234 } else if (M->getNamedValue(FunctionName)) {
4235 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004236 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004237
Dan Gohman399d6ae2009-08-29 23:37:49 +00004238 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004239 // If this is a definition of a forward referenced function, make sure the
4240 // types agree.
4241 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4242 = ForwardRefValIDs.find(NumberedVals.size());
4243 if (I != ForwardRefValIDs.end()) {
4244 Fn = cast<Function>(I->second.first);
4245 if (Fn->getType() != PFT)
4246 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004247 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004248 ForwardRefValIDs.erase(I);
4249 }
4250 }
4251
Craig Topper2617dcc2014-04-15 06:32:26 +00004252 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004253 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4254 else // Move the forward-reference to the correct spot in the module.
4255 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4256
4257 if (FunctionName.empty())
4258 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004259
Chris Lattnerac161bf2009-01-02 07:01:27 +00004260 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4261 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004262 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004263 Fn->setCallingConv(CC);
4264 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004265 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004266 Fn->setAlignment(Alignment);
4267 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004268 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004269 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004270 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004271 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004272 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004273 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004274
Chris Lattnerac161bf2009-01-02 07:01:27 +00004275 // Add all of the arguments we parsed to the function.
4276 Function::arg_iterator ArgIt = Fn->arg_begin();
4277 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4278 // If the argument has a name, insert it into the argument symbol table.
4279 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004280
Chris Lattnerac161bf2009-01-02 07:01:27 +00004281 // Set the name, if it conflicted, it will be auto-renamed.
4282 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004283
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004284 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004285 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4286 ArgList[i].Name + "'");
4287 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004288
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004289 if (isDefine)
4290 return false;
4291
Robin Morisset039781e2014-08-29 21:53:01 +00004292 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004293 ValID ID;
4294 if (FunctionName.empty()) {
4295 ID.Kind = ValID::t_GlobalID;
4296 ID.UIntVal = NumberedVals.size() - 1;
4297 } else {
4298 ID.Kind = ValID::t_GlobalName;
4299 ID.StrVal = FunctionName;
4300 }
4301 auto Blocks = ForwardRefBlockAddresses.find(ID);
4302 if (Blocks != ForwardRefBlockAddresses.end())
4303 return Error(Blocks->first.Loc,
4304 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004305 return false;
4306}
4307
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004308bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4309 ValID ID;
4310 if (FunctionNumber == -1) {
4311 ID.Kind = ValID::t_GlobalName;
4312 ID.StrVal = F.getName();
4313 } else {
4314 ID.Kind = ValID::t_GlobalID;
4315 ID.UIntVal = FunctionNumber;
4316 }
4317
4318 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4319 if (Blocks == P.ForwardRefBlockAddresses.end())
4320 return false;
4321
4322 for (const auto &I : Blocks->second) {
4323 const ValID &BBID = I.first;
4324 GlobalValue *GV = I.second;
4325
4326 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4327 "Expected local id or name");
4328 BasicBlock *BB;
4329 if (BBID.Kind == ValID::t_LocalName)
4330 BB = GetBB(BBID.StrVal, BBID.Loc);
4331 else
4332 BB = GetBB(BBID.UIntVal, BBID.Loc);
4333 if (!BB)
4334 return P.Error(BBID.Loc, "referenced value is not a basic block");
4335
4336 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4337 GV->eraseFromParent();
4338 }
4339
4340 P.ForwardRefBlockAddresses.erase(Blocks);
4341 return false;
4342}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004343
4344/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004345/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004346bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004347 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004348 return TokError("expected '{' in function body");
4349 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004350
Chris Lattner3432c622009-10-28 03:39:23 +00004351 int FunctionNumber = -1;
4352 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004353
Chris Lattner3432c622009-10-28 03:39:23 +00004354 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004355
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004356 // Resolve block addresses and allow basic blocks to be forward-declared
4357 // within this function.
4358 if (PFS.resolveForwardRefBlockAddresses())
4359 return true;
4360 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4361
Chris Lattnerbbddd962010-01-09 19:20:07 +00004362 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004363 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004364 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004365
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004366 while (Lex.getKind() != lltok::rbrace &&
4367 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004368 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004369
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004370 while (Lex.getKind() != lltok::rbrace)
4371 if (ParseUseListOrder(&PFS))
4372 return true;
4373
Chris Lattnerac161bf2009-01-02 07:01:27 +00004374 // Eat the }.
4375 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004376
Chris Lattnerac161bf2009-01-02 07:01:27 +00004377 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004378 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004379}
4380
4381/// ParseBasicBlock
4382/// ::= LabelStr? Instruction*
4383bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4384 // If this basic block starts out with a name, remember it.
4385 std::string Name;
4386 LocTy NameLoc = Lex.getLoc();
4387 if (Lex.getKind() == lltok::LabelStr) {
4388 Name = Lex.getStrVal();
4389 Lex.Lex();
4390 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004391
Chris Lattnerac161bf2009-01-02 07:01:27 +00004392 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004393 if (!BB)
4394 return Error(NameLoc,
4395 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004396
Chris Lattnerac161bf2009-01-02 07:01:27 +00004397 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004398
Chris Lattnerac161bf2009-01-02 07:01:27 +00004399 // Parse the instructions in this block until we get a terminator.
4400 Instruction *Inst;
4401 do {
4402 // This instruction may have three possibilities for a name: a) none
4403 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4404 LocTy NameLoc = Lex.getLoc();
4405 int NameID = -1;
4406 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004407
Chris Lattnerac161bf2009-01-02 07:01:27 +00004408 if (Lex.getKind() == lltok::LocalVarID) {
4409 NameID = Lex.getUIntVal();
4410 Lex.Lex();
4411 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4412 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004413 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004414 NameStr = Lex.getStrVal();
4415 Lex.Lex();
4416 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4417 return true;
4418 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004419
Chris Lattner77b89dc2009-12-30 05:23:43 +00004420 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004421 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004422 case InstError: return true;
4423 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004424 BB->getInstList().push_back(Inst);
4425
Chris Lattner77b89dc2009-12-30 05:23:43 +00004426 // With a normal result, we check to see if the instruction is followed by
4427 // a comma and metadata.
4428 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004429 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004430 return true;
4431 break;
4432 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004433 BB->getInstList().push_back(Inst);
4434
Chris Lattner77b89dc2009-12-30 05:23:43 +00004435 // If the instruction parser ate an extra comma at the end of it, it
4436 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004437 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004438 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004439 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004440 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004441
Chris Lattnerac161bf2009-01-02 07:01:27 +00004442 // Set the name on the instruction.
4443 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4444 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004445
Chris Lattnerac161bf2009-01-02 07:01:27 +00004446 return false;
4447}
4448
4449//===----------------------------------------------------------------------===//
4450// Instruction Parsing.
4451//===----------------------------------------------------------------------===//
4452
4453/// ParseInstruction - Parse one of the many different instructions.
4454///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004455int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4456 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004457 lltok::Kind Token = Lex.getKind();
4458 if (Token == lltok::Eof)
4459 return TokError("found end of file when expecting more instructions");
4460 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004461 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004462 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004463
Chris Lattnerac161bf2009-01-02 07:01:27 +00004464 switch (Token) {
4465 default: return Error(Loc, "expected instruction opcode");
4466 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004467 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004468 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4469 case lltok::kw_br: return ParseBr(Inst, PFS);
4470 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004471 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004472 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004473 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004474 // Binary Operators.
4475 case lltok::kw_add:
4476 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004477 case lltok::kw_mul:
4478 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004479 bool NUW = EatIfPresent(lltok::kw_nuw);
4480 bool NSW = EatIfPresent(lltok::kw_nsw);
4481 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004482
Chris Lattnera676c0f2011-02-07 16:40:21 +00004483 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004484
Chris Lattnera676c0f2011-02-07 16:40:21 +00004485 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4486 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4487 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004488 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004489 case lltok::kw_fadd:
4490 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004491 case lltok::kw_fmul:
4492 case lltok::kw_fdiv:
4493 case lltok::kw_frem: {
4494 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4495 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4496 if (Res != 0)
4497 return Res;
4498 if (FMF.any())
4499 Inst->setFastMathFlags(FMF);
4500 return 0;
4501 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004502
Chris Lattner35315d02011-02-06 21:44:57 +00004503 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004504 case lltok::kw_udiv:
4505 case lltok::kw_lshr:
4506 case lltok::kw_ashr: {
4507 bool Exact = EatIfPresent(lltok::kw_exact);
4508
4509 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4510 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4511 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004512 }
4513
Chris Lattnerac161bf2009-01-02 07:01:27 +00004514 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004515 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004516 case lltok::kw_and:
4517 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004518 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004519 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004520 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004521 // Casts.
4522 case lltok::kw_trunc:
4523 case lltok::kw_zext:
4524 case lltok::kw_sext:
4525 case lltok::kw_fptrunc:
4526 case lltok::kw_fpext:
4527 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004528 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004529 case lltok::kw_uitofp:
4530 case lltok::kw_sitofp:
4531 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004532 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004533 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004534 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004535 // Other.
4536 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004537 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004538 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4539 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4540 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4541 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004542 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004543 // Call.
4544 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4545 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4546 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004547 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004548 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004549 case lltok::kw_load: return ParseLoad(Inst, PFS);
4550 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004551 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4552 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004553 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004554 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4555 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4556 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4557 }
4558}
4559
4560/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4561bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004562 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004563 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004564 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004565 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4566 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4567 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4568 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4569 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4570 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4571 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4572 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4573 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4574 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4575 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4576 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4577 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4578 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4579 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4580 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4581 }
4582 } else {
4583 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004584 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004585 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4586 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4587 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4588 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4589 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4590 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4591 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4592 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4593 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4594 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4595 }
4596 }
4597 Lex.Lex();
4598 return false;
4599}
4600
4601//===----------------------------------------------------------------------===//
4602// Terminator Instructions.
4603//===----------------------------------------------------------------------===//
4604
4605/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004606/// ::= 'ret' void (',' !dbg, !1)*
4607/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004608bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004609 PerFunctionState &PFS) {
4610 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004611 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004612 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004613
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004614 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004615
Chris Lattnerfdd87902009-10-05 05:54:46 +00004616 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004617 if (!ResType->isVoidTy())
4618 return Error(TypeLoc, "value doesn't match function result type '" +
4619 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004620
Owen Anderson55f1c092009-08-13 21:58:54 +00004621 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004622 return false;
4623 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004624
Chris Lattnerac161bf2009-01-02 07:01:27 +00004625 Value *RV;
4626 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004627
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004628 if (ResType != RV->getType())
4629 return Error(TypeLoc, "value doesn't match function result type '" +
4630 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004631
Owen Anderson55f1c092009-08-13 21:58:54 +00004632 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004633 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004634}
4635
4636
4637/// ParseBr
4638/// ::= 'br' TypeAndValue
4639/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4640bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4641 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004642 Value *Op0;
4643 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004644 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004645
Chris Lattnerac161bf2009-01-02 07:01:27 +00004646 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4647 Inst = BranchInst::Create(BB);
4648 return false;
4649 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004650
Owen Anderson55f1c092009-08-13 21:58:54 +00004651 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004652 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004653
Chris Lattnerac161bf2009-01-02 07:01:27 +00004654 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004655 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004656 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004657 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004658 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004659
Chris Lattner3ed871f2009-10-27 19:13:16 +00004660 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004661 return false;
4662}
4663
4664/// ParseSwitch
4665/// Instruction
4666/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4667/// JumpTable
4668/// ::= (TypeAndValue ',' TypeAndValue)*
4669bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4670 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004671 Value *Cond;
4672 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004673 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4674 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004675 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004676 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4677 return true;
4678
Duncan Sands19d0b472010-02-16 11:11:14 +00004679 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004680 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004681
Chris Lattnerac161bf2009-01-02 07:01:27 +00004682 // Parse the jump table pairs.
4683 SmallPtrSet<Value*, 32> SeenCases;
4684 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4685 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004686 Value *Constant;
4687 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004688
Chris Lattnerac161bf2009-01-02 07:01:27 +00004689 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4690 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004691 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004692 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004693
David Blaikie70573dc2014-11-19 07:49:26 +00004694 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004695 return Error(CondLoc, "duplicate case value in switch");
4696 if (!isa<ConstantInt>(Constant))
4697 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004698
Chris Lattner3ed871f2009-10-27 19:13:16 +00004699 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004700 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004701
Chris Lattnerac161bf2009-01-02 07:01:27 +00004702 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004703
Chris Lattner3ed871f2009-10-27 19:13:16 +00004704 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004705 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4706 SI->addCase(Table[i].first, Table[i].second);
4707 Inst = SI;
4708 return false;
4709}
4710
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004711/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00004712/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004713/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4714bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004715 LocTy AddrLoc;
4716 Value *Address;
4717 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004718 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4719 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00004720 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004721
Duncan Sands19d0b472010-02-16 11:11:14 +00004722 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004723 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004724
Chris Lattner3ed871f2009-10-27 19:13:16 +00004725 // Parse the destination list.
4726 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004727
Chris Lattner3ed871f2009-10-27 19:13:16 +00004728 if (Lex.getKind() != lltok::rsquare) {
4729 BasicBlock *DestBB;
4730 if (ParseTypeAndBasicBlock(DestBB, PFS))
4731 return true;
4732 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004733
Chris Lattner3ed871f2009-10-27 19:13:16 +00004734 while (EatIfPresent(lltok::comma)) {
4735 if (ParseTypeAndBasicBlock(DestBB, PFS))
4736 return true;
4737 DestList.push_back(DestBB);
4738 }
4739 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004740
Chris Lattner3ed871f2009-10-27 19:13:16 +00004741 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4742 return true;
4743
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004744 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00004745 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4746 IBI->addDestination(DestList[i]);
4747 Inst = IBI;
4748 return false;
4749}
4750
4751
Chris Lattnerac161bf2009-01-02 07:01:27 +00004752/// ParseInvoke
4753/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4754/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4755bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4756 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00004757 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004758 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00004759 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004760 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004761 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004762 LocTy RetTypeLoc;
4763 ValID CalleeID;
4764 SmallVector<ParamInfo, 16> ArgList;
4765
Chris Lattner3ed871f2009-10-27 19:13:16 +00004766 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004767 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004768 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004769 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004770 ParseValID(CalleeID) ||
4771 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004772 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4773 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004774 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004775 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004776 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004777 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004778 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004779
Chris Lattnerac161bf2009-01-02 07:01:27 +00004780 // If RetType is a non-function pointer type, then this is the short syntax
4781 // for the call, which means that RetType is just the return type. Infer the
4782 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00004783 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4784 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004785 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004786 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004787 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4788 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004789
Chris Lattnerac161bf2009-01-02 07:01:27 +00004790 if (!FunctionType::isValidReturnType(RetType))
4791 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004792
Owen Anderson4056ca92009-07-29 22:17:13 +00004793 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004794 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004795
Chris Lattnerac161bf2009-01-02 07:01:27 +00004796 // Look up the callee.
4797 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00004798 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4799 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004800
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004801 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004802 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004803 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004804 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4805 AttributeSet::ReturnIndex,
4806 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004807
Chris Lattnerac161bf2009-01-02 07:01:27 +00004808 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004809
Chris Lattnerac161bf2009-01-02 07:01:27 +00004810 // Loop through FunctionType's arguments and ensure they are specified
4811 // correctly. Also, gather any parameter attributes.
4812 FunctionType::param_iterator I = Ty->param_begin();
4813 FunctionType::param_iterator E = Ty->param_end();
4814 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004815 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004816 if (I != E) {
4817 ExpectedTy = *I++;
4818 } else if (!Ty->isVarArg()) {
4819 return Error(ArgList[i].Loc, "too many arguments specified");
4820 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004821
Chris Lattnerac161bf2009-01-02 07:01:27 +00004822 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4823 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004824 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004825 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004826 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4827 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004828 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4829 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004830 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004831
Chris Lattnerac161bf2009-01-02 07:01:27 +00004832 if (I != E)
4833 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004834
David Majnemer8d22abd2015-02-23 00:01:32 +00004835 if (FnAttrs.hasAttributes()) {
4836 if (FnAttrs.hasAlignmentAttr())
4837 return Error(CallLoc, "invoke instructions may not have an alignment");
4838
Bill Wendlingf5075a42013-01-27 02:24:02 +00004839 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4840 AttributeSet::FunctionIndex,
4841 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00004842 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004843
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004844 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004845 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004846
David Blaikie3e807092015-05-13 18:35:26 +00004847 InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004848 II->setCallingConv(CC);
4849 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004850 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004851 Inst = II;
4852 return false;
4853}
4854
Bill Wendlingf891bf82011-07-31 06:30:59 +00004855/// ParseResume
4856/// ::= 'resume' TypeAndValue
4857bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4858 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004859 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4860 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004861
Bill Wendlingf891bf82011-07-31 06:30:59 +00004862 ResumeInst *RI = ResumeInst::Create(Exn);
4863 Inst = RI;
4864 return false;
4865}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004866
4867//===----------------------------------------------------------------------===//
4868// Binary Operators.
4869//===----------------------------------------------------------------------===//
4870
4871/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004872/// ::= ArithmeticOps TypeAndValue ',' Value
4873///
4874/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4875/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00004876bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004877 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004878 LocTy Loc; Value *LHS, *RHS;
4879 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4880 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4881 ParseValue(LHS->getType(), RHS, PFS))
4882 return true;
4883
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004884 bool Valid;
4885 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00004886 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004887 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00004888 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4889 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004890 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00004891 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4892 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004893 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004894
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004895 if (!Valid)
4896 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004897
Chris Lattnerac161bf2009-01-02 07:01:27 +00004898 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4899 return false;
4900}
4901
4902/// ParseLogical
4903/// ::= ArithmeticOps TypeAndValue ',' Value {
4904bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4905 unsigned Opc) {
4906 LocTy Loc; Value *LHS, *RHS;
4907 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4908 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4909 ParseValue(LHS->getType(), RHS, PFS))
4910 return true;
4911
Duncan Sands9dff9be2010-02-15 16:12:20 +00004912 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004913 return Error(Loc,"instruction requires integer or integer vector operands");
4914
4915 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4916 return false;
4917}
4918
4919
4920/// ParseCompare
4921/// ::= 'icmp' IPredicates TypeAndValue ',' Value
4922/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004923bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4924 unsigned Opc) {
4925 // Parse the integer/fp comparison predicate.
4926 LocTy Loc;
4927 unsigned Pred;
4928 Value *LHS, *RHS;
4929 if (ParseCmpPredicate(Pred, Opc) ||
4930 ParseTypeAndValue(LHS, Loc, PFS) ||
4931 ParseToken(lltok::comma, "expected ',' after compare value") ||
4932 ParseValue(LHS->getType(), RHS, PFS))
4933 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004934
Chris Lattnerac161bf2009-01-02 07:01:27 +00004935 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00004936 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004937 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004938 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004939 } else {
4940 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00004941 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00004942 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004943 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004944 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004945 }
4946 return false;
4947}
4948
4949//===----------------------------------------------------------------------===//
4950// Other Instructions.
4951//===----------------------------------------------------------------------===//
4952
4953
4954/// ParseCast
4955/// ::= CastOpc TypeAndValue 'to' Type
4956bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4957 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004958 LocTy Loc;
4959 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004960 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004961 if (ParseTypeAndValue(Op, Loc, PFS) ||
4962 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4963 ParseType(DestTy))
4964 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004965
Chris Lattner89d856e2009-03-01 00:53:13 +00004966 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4967 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004968 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004969 getTypeString(Op->getType()) + "' to '" +
4970 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004971 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004972 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4973 return false;
4974}
4975
4976/// ParseSelect
4977/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4978bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4979 LocTy Loc;
4980 Value *Op0, *Op1, *Op2;
4981 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4982 ParseToken(lltok::comma, "expected ',' after select condition") ||
4983 ParseTypeAndValue(Op1, PFS) ||
4984 ParseToken(lltok::comma, "expected ',' after select value") ||
4985 ParseTypeAndValue(Op2, PFS))
4986 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004987
Chris Lattnerac161bf2009-01-02 07:01:27 +00004988 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4989 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004990
Chris Lattnerac161bf2009-01-02 07:01:27 +00004991 Inst = SelectInst::Create(Op0, Op1, Op2);
4992 return false;
4993}
4994
Chris Lattnerb55ab542009-01-05 08:18:44 +00004995/// ParseVA_Arg
4996/// ::= 'va_arg' TypeAndValue ',' Type
4997bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004998 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004999 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005000 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005001 if (ParseTypeAndValue(Op, PFS) ||
5002 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005003 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005004 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005005
Chris Lattnerb55ab542009-01-05 08:18:44 +00005006 if (!EltTy->isFirstClassType())
5007 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005008
5009 Inst = new VAArgInst(Op, EltTy);
5010 return false;
5011}
5012
5013/// ParseExtractElement
5014/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5015bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5016 LocTy Loc;
5017 Value *Op0, *Op1;
5018 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5019 ParseToken(lltok::comma, "expected ',' after extract value") ||
5020 ParseTypeAndValue(Op1, PFS))
5021 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005022
Chris Lattnerac161bf2009-01-02 07:01:27 +00005023 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5024 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005025
Eric Christopherc9742252009-07-25 02:28:41 +00005026 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005027 return false;
5028}
5029
5030/// ParseInsertElement
5031/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5032bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5033 LocTy Loc;
5034 Value *Op0, *Op1, *Op2;
5035 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5036 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5037 ParseTypeAndValue(Op1, PFS) ||
5038 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5039 ParseTypeAndValue(Op2, PFS))
5040 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005041
Chris Lattnerac161bf2009-01-02 07:01:27 +00005042 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005043 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005044
Chris Lattnerac161bf2009-01-02 07:01:27 +00005045 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5046 return false;
5047}
5048
5049/// ParseShuffleVector
5050/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5051bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5052 LocTy Loc;
5053 Value *Op0, *Op1, *Op2;
5054 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5055 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5056 ParseTypeAndValue(Op1, PFS) ||
5057 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5058 ParseTypeAndValue(Op2, PFS))
5059 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005060
Chris Lattnerac161bf2009-01-02 07:01:27 +00005061 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005062 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005063
Chris Lattnerac161bf2009-01-02 07:01:27 +00005064 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5065 return false;
5066}
5067
5068/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005069/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005070int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005071 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005072 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005073
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005074 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005075 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5076 ParseValue(Ty, Op0, PFS) ||
5077 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005078 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005079 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5080 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005081
Chris Lattnerf4f03422009-12-30 05:27:33 +00005082 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005083 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5084 while (1) {
5085 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005086
Chris Lattner3822f632009-01-02 08:05:26 +00005087 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005088 break;
5089
Chris Lattnerf4f03422009-12-30 05:27:33 +00005090 if (Lex.getKind() == lltok::MetadataVar) {
5091 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005092 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005093 }
Devang Patel8f842d32009-10-16 18:45:49 +00005094
Chris Lattner3822f632009-01-02 08:05:26 +00005095 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005096 ParseValue(Ty, Op0, PFS) ||
5097 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005098 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005099 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5100 return true;
5101 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005102
Chris Lattnerac161bf2009-01-02 07:01:27 +00005103 if (!Ty->isFirstClassType())
5104 return Error(TypeLoc, "phi node must have first class type");
5105
Jay Foad52131342011-03-30 11:28:46 +00005106 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005107 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5108 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5109 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005110 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005111}
5112
Bill Wendlingfae14752011-08-12 20:24:12 +00005113/// ParseLandingPad
5114/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5115/// Clause
5116/// ::= 'catch' TypeAndValue
5117/// ::= 'filter'
5118/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5119bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005120 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005121
David Majnemer7fddecc2015-06-17 20:52:32 +00005122 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005123 return true;
5124
David Majnemer7fddecc2015-06-17 20:52:32 +00005125 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005126 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5127
5128 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5129 LandingPadInst::ClauseType CT;
5130 if (EatIfPresent(lltok::kw_catch))
5131 CT = LandingPadInst::Catch;
5132 else if (EatIfPresent(lltok::kw_filter))
5133 CT = LandingPadInst::Filter;
5134 else
5135 return TokError("expected 'catch' or 'filter' clause type");
5136
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005137 Value *V;
5138 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005139 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005140 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005141
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005142 // A 'catch' type expects a non-array constant. A filter clause expects an
5143 // array constant.
5144 if (CT == LandingPadInst::Catch) {
5145 if (isa<ArrayType>(V->getType()))
5146 Error(VLoc, "'catch' clause has an invalid type");
5147 } else {
5148 if (!isa<ArrayType>(V->getType()))
5149 Error(VLoc, "'filter' clause has an invalid type");
5150 }
5151
Owen Andersonf8f259d2015-03-09 07:13:42 +00005152 Constant *CV = dyn_cast<Constant>(V);
5153 if (!CV)
5154 return Error(VLoc, "clause argument must be a constant");
5155 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005156 }
5157
Owen Andersonf8f259d2015-03-09 07:13:42 +00005158 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005159 return false;
5160}
5161
Chris Lattnerac161bf2009-01-02 07:01:27 +00005162/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00005163/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5164/// ParameterList OptionalAttrs
5165/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5166/// ParameterList OptionalAttrs
5167/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005168/// ParameterList OptionalAttrs
5169bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005170 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005171 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005172 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005173 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005174 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005175 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005176 LocTy RetTypeLoc;
5177 ValID CalleeID;
5178 SmallVector<ParamInfo, 16> ArgList;
5179 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005180
Reid Kleckner5772b772014-04-24 20:14:34 +00005181 if ((TCK != CallInst::TCK_None &&
5182 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005183 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00005184 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005185 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005186 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005187 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5188 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005189 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005190 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005191 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005192
Chris Lattnerac161bf2009-01-02 07:01:27 +00005193 // If RetType is a non-function pointer type, then this is the short syntax
5194 // for the call, which means that RetType is just the return type. Infer the
5195 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005196 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5197 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005198 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005199 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005200 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5201 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005202
Chris Lattnerac161bf2009-01-02 07:01:27 +00005203 if (!FunctionType::isValidReturnType(RetType))
5204 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005205
Owen Anderson4056ca92009-07-29 22:17:13 +00005206 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005207 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005208
Chris Lattnerac161bf2009-01-02 07:01:27 +00005209 // Look up the callee.
5210 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005211 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5212 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005213
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005214 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005215 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005216 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005217 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5218 AttributeSet::ReturnIndex,
5219 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005220
Chris Lattnerac161bf2009-01-02 07:01:27 +00005221 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005222
Chris Lattnerac161bf2009-01-02 07:01:27 +00005223 // Loop through FunctionType's arguments and ensure they are specified
5224 // correctly. Also, gather any parameter attributes.
5225 FunctionType::param_iterator I = Ty->param_begin();
5226 FunctionType::param_iterator E = Ty->param_end();
5227 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005228 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005229 if (I != E) {
5230 ExpectedTy = *I++;
5231 } else if (!Ty->isVarArg()) {
5232 return Error(ArgList[i].Loc, "too many arguments specified");
5233 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005234
Chris Lattnerac161bf2009-01-02 07:01:27 +00005235 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5236 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005237 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005238 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005239 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5240 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005241 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5242 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005243 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005244
Chris Lattnerac161bf2009-01-02 07:01:27 +00005245 if (I != E)
5246 return Error(CallLoc, "not enough parameters specified for call");
5247
David Majnemer8d22abd2015-02-23 00:01:32 +00005248 if (FnAttrs.hasAttributes()) {
5249 if (FnAttrs.hasAlignmentAttr())
5250 return Error(CallLoc, "call instructions may not have an alignment");
5251
Bill Wendlingf5075a42013-01-27 02:24:02 +00005252 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5253 AttributeSet::FunctionIndex,
5254 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005255 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005256
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005257 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005258 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005259
David Blaikie348de692015-04-23 21:36:23 +00005260 CallInst *CI = CallInst::Create(Ty, Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00005261 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005262 CI->setCallingConv(CC);
5263 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005264 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005265 Inst = CI;
5266 return false;
5267}
5268
5269//===----------------------------------------------------------------------===//
5270// Memory Instructions.
5271//===----------------------------------------------------------------------===//
5272
5273/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00005274/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005275int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005276 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005277 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005278 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005279 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005280
5281 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5282
David Majnemera3b0eb22015-02-16 08:38:03 +00005283 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005284
David Majnemera3b0eb22015-02-16 08:38:03 +00005285 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5286 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005287
Chris Lattnerb2f39502009-12-30 05:44:30 +00005288 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005289 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005290 if (Lex.getKind() == lltok::kw_align) {
5291 if (ParseOptionalAlignment(Alignment)) return true;
5292 } else if (Lex.getKind() == lltok::MetadataVar) {
5293 AteExtraComma = true;
5294 } else {
5295 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5296 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5297 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005298 }
5299 }
5300
Dan Gohman2140a742010-05-28 01:14:11 +00005301 if (Size && !Size->getType()->isIntegerTy())
5302 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005303
Reid Kleckner436c42e2014-01-17 23:58:17 +00005304 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5305 AI->setUsedWithInAlloca(IsInAlloca);
5306 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005307 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005308}
5309
5310/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005311/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005312/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005313/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005314int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005315 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005316 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005317 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005318 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005319 AtomicOrdering Ordering = NotAtomic;
5320 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005321
5322 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005323 isAtomic = true;
5324 Lex.Lex();
5325 }
5326
Chris Lattnerbc639292011-11-27 06:56:53 +00005327 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005328 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005329 isVolatile = true;
5330 Lex.Lex();
5331 }
5332
David Blaikie15d9a4c2015-04-06 20:59:48 +00005333 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005334 LocTy ExplicitTypeLoc = Lex.getLoc();
5335 if (ParseType(Ty) ||
5336 ParseToken(lltok::comma, "expected comma after load's type") ||
5337 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005338 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005339 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5340 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005341
David Blaikie15d9a4c2015-04-06 20:59:48 +00005342 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005343 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005344 if (isAtomic && !Alignment)
5345 return Error(Loc, "atomic load must have explicit non-zero alignment");
5346 if (Ordering == Release || Ordering == AcquireRelease)
5347 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005348
David Blaikiea79ac142015-02-27 21:17:42 +00005349 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5350 return Error(ExplicitTypeLoc,
5351 "explicit pointee type doesn't match operand's pointee type");
5352
David Blaikie15d9a4c2015-04-06 20:59:48 +00005353 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005354 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005355}
5356
5357/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005358
5359/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5360/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005361/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005362int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005363 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005364 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005365 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005366 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005367 AtomicOrdering Ordering = NotAtomic;
5368 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005369
5370 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005371 isAtomic = true;
5372 Lex.Lex();
5373 }
5374
Chris Lattnerbc639292011-11-27 06:56:53 +00005375 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005376 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005377 isVolatile = true;
5378 Lex.Lex();
5379 }
5380
Chris Lattnerac161bf2009-01-02 07:01:27 +00005381 if (ParseTypeAndValue(Val, Loc, PFS) ||
5382 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005383 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005384 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005385 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005386 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005387
Duncan Sands19d0b472010-02-16 11:11:14 +00005388 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005389 return Error(PtrLoc, "store operand must be a pointer");
5390 if (!Val->getType()->isFirstClassType())
5391 return Error(Loc, "store operand must be a first class value");
5392 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5393 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005394 if (isAtomic && !Alignment)
5395 return Error(Loc, "atomic store must have explicit non-zero alignment");
5396 if (Ordering == Acquire || Ordering == AcquireRelease)
5397 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005398
Eli Friedman59b66882011-08-09 23:02:53 +00005399 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005400 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005401}
5402
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005403/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005404/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5405/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005406int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005407 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5408 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005409 AtomicOrdering SuccessOrdering = NotAtomic;
5410 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005411 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005412 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005413 bool isWeak = false;
5414
5415 if (EatIfPresent(lltok::kw_weak))
5416 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005417
5418 if (EatIfPresent(lltok::kw_volatile))
5419 isVolatile = true;
5420
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005421 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5422 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5423 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5424 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5425 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005426 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5427 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005428 return true;
5429
Tim Northovere94a5182014-03-11 10:48:52 +00005430 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005431 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005432 if (SuccessOrdering < FailureOrdering)
5433 return TokError("cmpxchg must be at least as ordered on success as failure");
5434 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5435 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005436 if (!Ptr->getType()->isPointerTy())
5437 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5438 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5439 return Error(CmpLoc, "compare value and pointer type do not match");
5440 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5441 return Error(NewLoc, "new value and pointer type do not match");
5442 if (!New->getType()->isIntegerTy())
5443 return Error(NewLoc, "cmpxchg operand must be an integer");
5444 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5445 if (Size < 8 || (Size & (Size - 1)))
5446 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5447 " integer");
5448
Tim Northover420a2162014-06-13 14:24:07 +00005449 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5450 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005451 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00005452 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005453 Inst = CXI;
5454 return AteExtraComma ? InstExtraComma : InstNormal;
5455}
5456
5457/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00005458/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5459/// 'singlethread'? AtomicOrdering
5460int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005461 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5462 bool AteExtraComma = false;
5463 AtomicOrdering Ordering = NotAtomic;
5464 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005465 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005466 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00005467
5468 if (EatIfPresent(lltok::kw_volatile))
5469 isVolatile = true;
5470
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005471 switch (Lex.getKind()) {
5472 default: return TokError("expected binary operation in atomicrmw");
5473 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5474 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5475 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5476 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5477 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5478 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5479 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5480 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5481 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5482 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5483 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5484 }
5485 Lex.Lex(); // Eat the operation.
5486
5487 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5488 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5489 ParseTypeAndValue(Val, ValLoc, PFS) ||
5490 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5491 return true;
5492
5493 if (Ordering == Unordered)
5494 return TokError("atomicrmw cannot be unordered");
5495 if (!Ptr->getType()->isPointerTy())
5496 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5497 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5498 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5499 if (!Val->getType()->isIntegerTy())
5500 return Error(ValLoc, "atomicrmw operand must be an integer");
5501 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5502 if (Size < 8 || (Size & (Size - 1)))
5503 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5504 " integer");
5505
5506 AtomicRMWInst *RMWI =
5507 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5508 RMWI->setVolatile(isVolatile);
5509 Inst = RMWI;
5510 return AteExtraComma ? InstExtraComma : InstNormal;
5511}
5512
Eli Friedmanfee02c62011-07-25 23:16:38 +00005513/// ParseFence
5514/// ::= 'fence' 'singlethread'? AtomicOrdering
5515int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5516 AtomicOrdering Ordering = NotAtomic;
5517 SynchronizationScope Scope = CrossThread;
5518 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5519 return true;
5520
5521 if (Ordering == Unordered)
5522 return TokError("fence cannot be unordered");
5523 if (Ordering == Monotonic)
5524 return TokError("fence cannot be monotonic");
5525
5526 Inst = new FenceInst(Context, Ordering, Scope);
5527 return InstNormal;
5528}
5529
Chris Lattnerac161bf2009-01-02 07:01:27 +00005530/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00005531/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005532int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005533 Value *Ptr = nullptr;
5534 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005535 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00005536
Dan Gohman16cbbe42009-07-29 15:58:36 +00005537 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00005538
David Blaikie79e6c742015-02-27 19:29:02 +00005539 Type *Ty = nullptr;
5540 LocTy ExplicitTypeLoc = Lex.getLoc();
5541 if (ParseType(Ty) ||
5542 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5543 ParseTypeAndValue(Ptr, Loc, PFS))
5544 return true;
5545
Eli Benderskyd9806682013-04-22 17:03:42 +00005546 Type *BaseType = Ptr->getType();
5547 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5548 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005549 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005550
David Blaikie8d757942015-03-09 23:08:44 +00005551 if (Ty != BasePointerType->getElementType())
5552 return Error(ExplicitTypeLoc,
5553 "explicit pointee type doesn't match operand's pointee type");
5554
Chris Lattnerac161bf2009-01-02 07:01:27 +00005555 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005556 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005557 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00005558 if (Lex.getKind() == lltok::MetadataVar) {
5559 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00005560 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005561 }
Chris Lattner3822f632009-01-02 08:05:26 +00005562 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005563 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005564 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem3924cb02011-12-05 06:29:09 +00005565 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
5566 return Error(EltLoc, "getelementptr index type missmatch");
5567 if (Val->getType()->isVectorTy()) {
5568 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
5569 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
5570 if (ValNumEl != PtrNumEl)
5571 return Error(EltLoc,
5572 "getelementptr vector index has a wrong number of elements");
5573 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005574 Indices.push_back(Val);
5575 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005576
Owen Andersone90f9922015-03-10 06:34:57 +00005577 SmallPtrSet<const Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00005578 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00005579 return Error(Loc, "base element of getelementptr must be sized");
5580
David Blaikied33bad32015-04-17 22:32:13 +00005581 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005582 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00005583 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00005584 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00005585 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005586 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005587}
5588
5589/// ParseExtractValue
5590/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005591int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005592 Value *Val; LocTy Loc;
5593 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005594 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005595 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005596 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005597 return true;
5598
Chris Lattner392be582010-02-12 20:49:41 +00005599 if (!Val->getType()->isAggregateType())
5600 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005601
Jay Foad57aa6362011-07-13 10:26:04 +00005602 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005603 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00005604 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005605 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005606}
5607
5608/// ParseInsertValue
5609/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005610int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005611 Value *Val0, *Val1; LocTy Loc0, Loc1;
5612 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005613 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005614 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5615 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5616 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005617 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005618 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005619
Chris Lattner392be582010-02-12 20:49:41 +00005620 if (!Val0->getType()->isAggregateType())
5621 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005622
David Majnemer30074532015-02-11 07:43:58 +00005623 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5624 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005625 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00005626 if (IndexedType != Val1->getType())
5627 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5628 getTypeString(Val1->getType()) + "' instead of '" +
5629 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00005630 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005631 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005632}
Nick Lewycky49f89192009-04-04 07:22:01 +00005633
5634//===----------------------------------------------------------------------===//
5635// Embedded metadata.
5636//===----------------------------------------------------------------------===//
5637
5638/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005639/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005640/// Element
5641/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005642bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00005643 if (ParseToken(lltok::lbrace, "expected '{' here"))
5644 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005645
Dan Gohman1e0213a2010-07-13 19:33:27 +00005646 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005647 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00005648 return false;
5649
Nick Lewycky49f89192009-04-04 07:22:01 +00005650 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005651 // Null is a special case since it is typeless.
5652 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005653 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005654 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005655 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005656
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005657 Metadata *MD;
5658 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005659 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005660 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00005661 } while (EatIfPresent(lltok::comma));
5662
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005663 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00005664}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005665
5666//===----------------------------------------------------------------------===//
5667// Use-list order directives.
5668//===----------------------------------------------------------------------===//
5669bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5670 SMLoc Loc) {
5671 if (V->use_empty())
5672 return Error(Loc, "value has no uses");
5673
5674 unsigned NumUses = 0;
5675 SmallDenseMap<const Use *, unsigned, 16> Order;
5676 for (const Use &U : V->uses()) {
5677 if (++NumUses > Indexes.size())
5678 break;
5679 Order[&U] = Indexes[NumUses - 1];
5680 }
5681 if (NumUses < 2)
5682 return Error(Loc, "value only has one use");
5683 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5684 return Error(Loc, "wrong number of indexes, expected " +
5685 Twine(std::distance(V->use_begin(), V->use_end())));
5686
5687 V->sortUseList([&](const Use &L, const Use &R) {
5688 return Order.lookup(&L) < Order.lookup(&R);
5689 });
5690 return false;
5691}
5692
5693/// ParseUseListOrderIndexes
5694/// ::= '{' uint32 (',' uint32)+ '}'
5695bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5696 SMLoc Loc = Lex.getLoc();
5697 if (ParseToken(lltok::lbrace, "expected '{' here"))
5698 return true;
5699 if (Lex.getKind() == lltok::rbrace)
5700 return Lex.Error("expected non-empty list of uselistorder indexes");
5701
5702 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5703 // indexes should be distinct numbers in the range [0, size-1], and should
5704 // not be in order.
5705 unsigned Offset = 0;
5706 unsigned Max = 0;
5707 bool IsOrdered = true;
5708 assert(Indexes.empty() && "Expected empty order vector");
5709 do {
5710 unsigned Index;
5711 if (ParseUInt32(Index))
5712 return true;
5713
5714 // Update consistency checks.
5715 Offset += Index - Indexes.size();
5716 Max = std::max(Max, Index);
5717 IsOrdered &= Index == Indexes.size();
5718
5719 Indexes.push_back(Index);
5720 } while (EatIfPresent(lltok::comma));
5721
5722 if (ParseToken(lltok::rbrace, "expected '}' here"))
5723 return true;
5724
5725 if (Indexes.size() < 2)
5726 return Error(Loc, "expected >= 2 uselistorder indexes");
5727 if (Offset != 0 || Max >= Indexes.size())
5728 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5729 if (IsOrdered)
5730 return Error(Loc, "expected uselistorder indexes to change the order");
5731
5732 return false;
5733}
5734
5735/// ParseUseListOrder
5736/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5737bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5738 SMLoc Loc = Lex.getLoc();
5739 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5740 return true;
5741
5742 Value *V;
5743 SmallVector<unsigned, 16> Indexes;
5744 if (ParseTypeAndValue(V, PFS) ||
5745 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5746 ParseUseListOrderIndexes(Indexes))
5747 return true;
5748
5749 return sortUseListOrder(V, Indexes, Loc);
5750}
5751
5752/// ParseUseListOrderBB
5753/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5754bool LLParser::ParseUseListOrderBB() {
5755 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5756 SMLoc Loc = Lex.getLoc();
5757 Lex.Lex();
5758
5759 ValID Fn, Label;
5760 SmallVector<unsigned, 16> Indexes;
5761 if (ParseValID(Fn) ||
5762 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5763 ParseValID(Label) ||
5764 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5765 ParseUseListOrderIndexes(Indexes))
5766 return true;
5767
5768 // Check the function.
5769 GlobalValue *GV;
5770 if (Fn.Kind == ValID::t_GlobalName)
5771 GV = M->getNamedValue(Fn.StrVal);
5772 else if (Fn.Kind == ValID::t_GlobalID)
5773 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5774 else
5775 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5776 if (!GV)
5777 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5778 auto *F = dyn_cast<Function>(GV);
5779 if (!F)
5780 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5781 if (F->isDeclaration())
5782 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5783
5784 // Check the basic block.
5785 if (Label.Kind == ValID::t_LocalID)
5786 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5787 if (Label.Kind != ValID::t_LocalName)
5788 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5789 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5790 if (!V)
5791 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5792 if (!isa<BasicBlock>(V))
5793 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5794
5795 return sortUseListOrder(V, Indexes, Loc);
5796}