blob: 91a88bc91fd7bd6d1a8d868cdf1e2e0879132e29 [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()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00002876 unsigned ValNumEl = ValTy->getVectorNumElements();
2877 unsigned PtrNumEl = BaseType->getVectorNumElements();
David Majnemer00303b62015-02-22 23:14:52 +00002878 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
Adrian Prantlab1243f2015-06-29 23:03:47 +00003679/// ParseDIModule:
3680/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3681/// includePath: "/usr/include", isysroot: "/")
3682bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3683#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3684 REQUIRED(scope, MDField, ); \
3685 REQUIRED(name, MDStringField, ); \
3686 OPTIONAL(configMacros, MDStringField, ); \
3687 OPTIONAL(includePath, MDStringField, ); \
3688 OPTIONAL(isysroot, MDStringField, );
3689 PARSE_MD_FIELDS();
3690#undef VISIT_MD_FIELDS
3691
3692 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3693 configMacros.Val, includePath.Val, isysroot.Val));
3694 return false;
3695}
3696
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003697/// ParseDITemplateTypeParameter:
3698/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3699bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003700#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003701 OPTIONAL(name, MDStringField, ); \
3702 REQUIRED(type, MDField, );
3703 PARSE_MD_FIELDS();
3704#undef VISIT_MD_FIELDS
3705
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003706 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003707 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003708 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003709}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003710
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003711/// ParseDITemplateValueParameter:
3712/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003713/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003714bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003715#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003716 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003717 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003718 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003719 REQUIRED(value, MDField, );
3720 PARSE_MD_FIELDS();
3721#undef VISIT_MD_FIELDS
3722
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003723 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00003724 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003725 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003726}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00003727
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003728/// ParseDIGlobalVariable:
3729/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003730/// file: !1, line: 7, type: !2, isLocal: false,
3731/// isDefinition: true, variable: i32* @foo,
3732/// declaration: !3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003733bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003734#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003735 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003736 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003737 OPTIONAL(linkageName, MDStringField, ); \
3738 OPTIONAL(file, MDField, ); \
3739 OPTIONAL(line, LineField, ); \
3740 OPTIONAL(type, MDField, ); \
3741 OPTIONAL(isLocal, MDBoolField, ); \
3742 OPTIONAL(isDefinition, MDBoolField, (true)); \
3743 OPTIONAL(variable, MDConstant, ); \
3744 OPTIONAL(declaration, MDField, );
3745 PARSE_MD_FIELDS();
3746#undef VISIT_MD_FIELDS
3747
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003748 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003749 (Context, scope.Val, name.Val, linkageName.Val,
3750 file.Val, line.Val, type.Val, isLocal.Val,
3751 isDefinition.Val, variable.Val, declaration.Val));
3752 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003753}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00003754
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003755/// ParseDILocalVariable:
3756/// ::= !DILocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003757/// file: !1, line: 7, type: !2, arg: 2, flags: 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003758bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003759#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3760 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003761 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003762 OPTIONAL(name, MDStringField, ); \
3763 OPTIONAL(file, MDField, ); \
3764 OPTIONAL(line, LineField, ); \
3765 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith69488692015-06-02 17:17:44 +00003766 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003767 OPTIONAL(flags, DIFlagField, );
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003768 PARSE_MD_FIELDS();
3769#undef VISIT_MD_FIELDS
3770
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003771 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00003772 (Context, tag.Val, scope.Val, name.Val, file.Val,
3773 line.Val, type.Val, arg.Val, flags.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003774 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003775}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00003776
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003777/// ParseDIExpression:
3778/// ::= !DIExpression(0, 7, -1)
3779bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003780 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3781 Lex.Lex();
3782
3783 if (ParseToken(lltok::lparen, "expected '(' here"))
3784 return true;
3785
3786 SmallVector<uint64_t, 8> Elements;
3787 if (Lex.getKind() != lltok::rparen)
3788 do {
3789 if (Lex.getKind() == lltok::DwarfOp) {
3790 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3791 Lex.Lex();
3792 Elements.push_back(Op);
3793 continue;
3794 }
3795 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3796 }
3797
3798 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3799 return TokError("expected unsigned integer");
3800
3801 auto &U = Lex.getAPSIntVal();
3802 if (U.ugt(UINT64_MAX))
3803 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3804 Elements.push_back(U.getZExtValue());
3805 Lex.Lex();
3806 } while (EatIfPresent(lltok::comma));
3807
3808 if (ParseToken(lltok::rparen, "expected ')' here"))
3809 return true;
3810
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003811 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003812 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003813}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00003814
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003815/// ParseDIObjCProperty:
3816/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003817/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003818bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003819#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00003820 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003821 OPTIONAL(file, MDField, ); \
3822 OPTIONAL(line, LineField, ); \
3823 OPTIONAL(setter, MDStringField, ); \
3824 OPTIONAL(getter, MDStringField, ); \
3825 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3826 OPTIONAL(type, MDField, );
3827 PARSE_MD_FIELDS();
3828#undef VISIT_MD_FIELDS
3829
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003830 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003831 (Context, name.Val, file.Val, line.Val, setter.Val,
3832 getter.Val, attributes.Val, type.Val));
3833 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003834}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00003835
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003836/// ParseDIImportedEntity:
3837/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003838/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003839bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003840#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3841 REQUIRED(tag, DwarfTagField, ); \
3842 REQUIRED(scope, MDField, ); \
3843 OPTIONAL(entity, MDField, ); \
3844 OPTIONAL(line, LineField, ); \
3845 OPTIONAL(name, MDStringField, );
3846 PARSE_MD_FIELDS();
3847#undef VISIT_MD_FIELDS
3848
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003849 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003850 entity.Val, line.Val, name.Val));
3851 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003852}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00003853
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003854#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003855#undef NOP_FIELD
3856#undef REQUIRE_FIELD
3857#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003858
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003859/// ParseMetadataAsValue
3860/// ::= metadata i32 %local
3861/// ::= metadata i32 @global
3862/// ::= metadata i32 7
3863/// ::= metadata !0
3864/// ::= metadata !{...}
3865/// ::= metadata !"string"
3866bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3867 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003868 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003869 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003870 return true;
3871
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003872 V = MetadataAsValue::get(Context, MD);
3873 return false;
3874}
3875
3876/// ParseValueAsMetadata
3877/// ::= i32 %local
3878/// ::= i32 @global
3879/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003880bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3881 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003882 Type *Ty;
3883 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003884 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003885 return true;
3886 if (Ty->isMetadataTy())
3887 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3888
3889 Value *V;
3890 if (ParseValue(Ty, V, PFS))
3891 return true;
3892
3893 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003894 return false;
3895}
3896
3897/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003898/// ::= i32 %local
3899/// ::= i32 @global
3900/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00003901/// ::= !42
3902/// ::= !{...}
3903/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003904/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003905bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003906 if (Lex.getKind() == lltok::MetadataVar) {
3907 MDNode *N;
3908 if (ParseSpecializedMDNode(N))
3909 return true;
3910 MD = N;
3911 return false;
3912 }
3913
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003914 // ValueAsMetadata:
3915 // <type> <value>
3916 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003917 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003918
3919 // '!'.
3920 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3921 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00003922
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003923 // MDString:
3924 // ::= '!' STRINGCONSTANT
3925 if (Lex.getKind() == lltok::StringConstant) {
3926 MDString *S;
3927 if (ParseMDString(S))
3928 return true;
3929 MD = S;
3930 return false;
3931 }
3932
Dan Gohman8939ba332010-07-14 18:26:50 +00003933 // MDNode:
3934 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003935 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003936 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003937 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003938 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00003939 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00003940 return false;
3941}
3942
Victor Hernandez9d75c962010-01-11 22:31:58 +00003943
3944//===----------------------------------------------------------------------===//
3945// Function Parsing.
3946//===----------------------------------------------------------------------===//
3947
Chris Lattner229907c2011-07-18 04:54:35 +00003948bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez9d75c962010-01-11 22:31:58 +00003949 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00003950 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003951 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003952
Chris Lattnerac161bf2009-01-02 07:01:27 +00003953 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003954 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003955 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3956 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003957 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003958 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00003959 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3960 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003961 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003962 case ValID::t_InlineAsm: {
Chris Lattner229907c2011-07-18 04:54:35 +00003963 PointerType *PTy = dyn_cast<PointerType>(Ty);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003964 FunctionType *FTy =
Craig Topper2617dcc2014-04-15 06:32:26 +00003965 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003966 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3967 return Error(ID.Loc, "invalid type for inline asm constraint string");
Chad Rosierf42fad62012-09-05 00:08:17 +00003968 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
Chad Rosierd8c76102012-09-05 19:00:49 +00003969 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003970 return false;
3971 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003972 case ValID::t_GlobalName:
3973 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003974 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003975 case ValID::t_GlobalID:
3976 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003977 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003978 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00003979 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003980 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00003981 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00003982 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003983 return false;
3984 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00003985 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003986 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3987 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003988
Dan Gohman518cda42011-12-17 00:04:22 +00003989 // The lexer has no type info, so builds all half, float, and double FP
3990 // constants as double. Fix this here. Long double does not need this.
3991 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003992 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00003993 if (Ty->isHalfTy())
3994 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3995 &Ignored);
3996 else if (Ty->isFloatTy())
3997 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3998 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003999 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004000 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004001
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004002 if (V->getType() != Ty)
4003 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004004 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004005
Chris Lattnerac161bf2009-01-02 07:01:27 +00004006 return false;
4007 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004008 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004009 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004010 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004011 return false;
4012 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004013 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004014 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004015 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004016 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004017 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004018 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004019 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004020 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004021 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004022 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004023 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004024 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004025 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004026 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004027 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004028 return false;
4029 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004030 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004031 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004032
Chris Lattnerac161bf2009-01-02 07:01:27 +00004033 V = ID.ConstantVal;
4034 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004035 case ValID::t_ConstantStruct:
4036 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004037 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004038 if (ST->getNumElements() != ID.UIntVal)
4039 return Error(ID.Loc,
4040 "initializer with struct type has wrong # elements");
4041 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4042 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004043
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004044 // Verify that the elements are compatible with the structtype.
4045 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4046 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4047 return Error(ID.Loc, "element " + Twine(i) +
4048 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004049
Reid Kleckner2ae03e12015-03-04 18:31:10 +00004050 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4051 ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004052 } else
4053 return Error(ID.Loc, "constant expression type mismatch");
4054 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004055 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004056 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004057}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004058
Chris Lattner229907c2011-07-18 04:54:35 +00004059bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004060 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004061 ValID ID;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004062 return ParseValID(ID, PFS) ||
4063 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004064}
4065
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004066bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004067 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004068 return ParseType(Ty) ||
4069 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004070}
4071
Chris Lattner3ed871f2009-10-27 19:13:16 +00004072bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4073 PerFunctionState &PFS) {
4074 Value *V;
4075 Loc = Lex.getLoc();
4076 if (ParseTypeAndValue(V, PFS)) return true;
4077 if (!isa<BasicBlock>(V))
4078 return Error(Loc, "expected a basic block");
4079 BB = cast<BasicBlock>(V);
4080 return false;
4081}
4082
4083
Chris Lattnerac161bf2009-01-02 07:01:27 +00004084/// FunctionHeader
4085/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004086/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004087/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004088bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4089 // Parse the linkage.
4090 LocTy LinkageLoc = Lex.getLoc();
4091 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004092
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004093 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004094 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004095 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004096 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004097 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004098 LocTy RetTypeLoc = Lex.getLoc();
4099 if (ParseOptionalLinkage(Linkage) ||
4100 ParseOptionalVisibility(Visibility) ||
Nico Rieck7157bb72014-01-14 15:22:47 +00004101 ParseOptionalDLLStorageClass(DLLStorageClass) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004102 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004103 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004104 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004105 return true;
4106
4107 // Verify that the linkage is ok.
4108 switch ((GlobalValue::LinkageTypes)Linkage) {
4109 case GlobalValue::ExternalLinkage:
4110 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004111 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004112 if (isDefine)
4113 return Error(LinkageLoc, "invalid linkage for function definition");
4114 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004115 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004116 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004117 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004118 case GlobalValue::LinkOnceAnyLinkage:
4119 case GlobalValue::LinkOnceODRLinkage:
4120 case GlobalValue::WeakAnyLinkage:
4121 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004122 if (!isDefine)
4123 return Error(LinkageLoc, "invalid linkage for function declaration");
4124 break;
4125 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004126 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004127 return Error(LinkageLoc, "invalid function linkage type");
4128 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004129
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004130 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4131 return Error(LinkageLoc,
4132 "symbol with local linkage must have default visibility");
4133
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004134 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004135 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004136
Chris Lattnerac161bf2009-01-02 07:01:27 +00004137 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004138
4139 std::string FunctionName;
4140 if (Lex.getKind() == lltok::GlobalVar) {
4141 FunctionName = Lex.getStrVal();
4142 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4143 unsigned NameID = Lex.getUIntVal();
4144
4145 if (NameID != NumberedVals.size())
4146 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004147 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004148 } else {
4149 return TokError("expected function name");
4150 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004151
Chris Lattner3822f632009-01-02 08:05:26 +00004152 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004153
Chris Lattner3822f632009-01-02 08:05:26 +00004154 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004155 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004156
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004157 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004158 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004159 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004160 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004161 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004162 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004163 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004164 std::string GC;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004165 bool UnnamedAddr;
4166 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004167 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004168 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004169 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004170 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004171
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004172 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004173 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4174 &UnnamedAddrLoc) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004175 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004176 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004177 (EatIfPresent(lltok::kw_section) &&
4178 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004179 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004180 ParseOptionalAlignment(Alignment) ||
4181 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004182 ParseStringConstant(GC)) ||
4183 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004184 ParseGlobalTypeAndValue(Prefix)) ||
4185 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004186 ParseGlobalTypeAndValue(Prologue)) ||
4187 (EatIfPresent(lltok::kw_personality) &&
4188 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004189 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004190
Michael Gottesman41748d72013-06-27 00:25:01 +00004191 if (FuncAttrs.contains(Attribute::Builtin))
4192 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004193
Chris Lattnerac161bf2009-01-02 07:01:27 +00004194 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004195 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004196 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004197 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004198 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004199
Chris Lattnerac161bf2009-01-02 07:01:27 +00004200 // Okay, if we got here, the function is syntactically valid. Convert types
4201 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004202 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004203 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004204
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004205 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004206 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4207 AttributeSet::ReturnIndex,
4208 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004209
Chris Lattnerac161bf2009-01-02 07:01:27 +00004210 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004211 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004212 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4213 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004214 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4215 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004216 }
4217
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004218 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004219 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4220 AttributeSet::FunctionIndex,
4221 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004222
Bill Wendlinge94d8432012-12-07 23:16:57 +00004223 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004224
Bill Wendling749a43d2012-12-30 13:50:49 +00004225 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004226 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4227
Chris Lattner229907c2011-07-18 04:54:35 +00004228 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004229 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004230 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004231
Craig Topper2617dcc2014-04-15 06:32:26 +00004232 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004233 if (!FunctionName.empty()) {
4234 // If this was a definition of a forward reference, remove the definition
4235 // from the forward reference table and fill in the forward ref.
4236 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4237 ForwardRefVals.find(FunctionName);
4238 if (FRVI != ForwardRefVals.end()) {
4239 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004240 if (!Fn)
4241 return Error(FRVI->second.second, "invalid forward reference to "
4242 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004243 if (Fn->getType() != PFT)
4244 return Error(FRVI->second.second, "invalid forward reference to "
4245 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004246
Chris Lattnerac161bf2009-01-02 07:01:27 +00004247 ForwardRefVals.erase(FRVI);
4248 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004249 // Reject redefinitions.
4250 return Error(NameLoc, "invalid redefinition of function '" +
4251 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004252 } else if (M->getNamedValue(FunctionName)) {
4253 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004254 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004255
Dan Gohman399d6ae2009-08-29 23:37:49 +00004256 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004257 // If this is a definition of a forward referenced function, make sure the
4258 // types agree.
4259 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4260 = ForwardRefValIDs.find(NumberedVals.size());
4261 if (I != ForwardRefValIDs.end()) {
4262 Fn = cast<Function>(I->second.first);
4263 if (Fn->getType() != PFT)
4264 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004265 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004266 ForwardRefValIDs.erase(I);
4267 }
4268 }
4269
Craig Topper2617dcc2014-04-15 06:32:26 +00004270 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004271 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4272 else // Move the forward-reference to the correct spot in the module.
4273 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4274
4275 if (FunctionName.empty())
4276 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004277
Chris Lattnerac161bf2009-01-02 07:01:27 +00004278 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4279 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004280 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004281 Fn->setCallingConv(CC);
4282 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004283 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004284 Fn->setAlignment(Alignment);
4285 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004286 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004287 Fn->setPersonalityFn(PersonalityFn);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004288 if (!GC.empty()) Fn->setGC(GC.c_str());
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004289 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004290 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004291 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004292
Chris Lattnerac161bf2009-01-02 07:01:27 +00004293 // Add all of the arguments we parsed to the function.
4294 Function::arg_iterator ArgIt = Fn->arg_begin();
4295 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4296 // If the argument has a name, insert it into the argument symbol table.
4297 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004298
Chris Lattnerac161bf2009-01-02 07:01:27 +00004299 // Set the name, if it conflicted, it will be auto-renamed.
4300 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004301
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004302 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004303 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4304 ArgList[i].Name + "'");
4305 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004306
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004307 if (isDefine)
4308 return false;
4309
Robin Morisset039781e2014-08-29 21:53:01 +00004310 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004311 ValID ID;
4312 if (FunctionName.empty()) {
4313 ID.Kind = ValID::t_GlobalID;
4314 ID.UIntVal = NumberedVals.size() - 1;
4315 } else {
4316 ID.Kind = ValID::t_GlobalName;
4317 ID.StrVal = FunctionName;
4318 }
4319 auto Blocks = ForwardRefBlockAddresses.find(ID);
4320 if (Blocks != ForwardRefBlockAddresses.end())
4321 return Error(Blocks->first.Loc,
4322 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004323 return false;
4324}
4325
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004326bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4327 ValID ID;
4328 if (FunctionNumber == -1) {
4329 ID.Kind = ValID::t_GlobalName;
4330 ID.StrVal = F.getName();
4331 } else {
4332 ID.Kind = ValID::t_GlobalID;
4333 ID.UIntVal = FunctionNumber;
4334 }
4335
4336 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4337 if (Blocks == P.ForwardRefBlockAddresses.end())
4338 return false;
4339
4340 for (const auto &I : Blocks->second) {
4341 const ValID &BBID = I.first;
4342 GlobalValue *GV = I.second;
4343
4344 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4345 "Expected local id or name");
4346 BasicBlock *BB;
4347 if (BBID.Kind == ValID::t_LocalName)
4348 BB = GetBB(BBID.StrVal, BBID.Loc);
4349 else
4350 BB = GetBB(BBID.UIntVal, BBID.Loc);
4351 if (!BB)
4352 return P.Error(BBID.Loc, "referenced value is not a basic block");
4353
4354 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4355 GV->eraseFromParent();
4356 }
4357
4358 P.ForwardRefBlockAddresses.erase(Blocks);
4359 return false;
4360}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004361
4362/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004363/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004364bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004365 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004366 return TokError("expected '{' in function body");
4367 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004368
Chris Lattner3432c622009-10-28 03:39:23 +00004369 int FunctionNumber = -1;
4370 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004371
Chris Lattner3432c622009-10-28 03:39:23 +00004372 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004373
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004374 // Resolve block addresses and allow basic blocks to be forward-declared
4375 // within this function.
4376 if (PFS.resolveForwardRefBlockAddresses())
4377 return true;
4378 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4379
Chris Lattnerbbddd962010-01-09 19:20:07 +00004380 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004381 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004382 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004383
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004384 while (Lex.getKind() != lltok::rbrace &&
4385 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004386 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004387
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004388 while (Lex.getKind() != lltok::rbrace)
4389 if (ParseUseListOrder(&PFS))
4390 return true;
4391
Chris Lattnerac161bf2009-01-02 07:01:27 +00004392 // Eat the }.
4393 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004394
Chris Lattnerac161bf2009-01-02 07:01:27 +00004395 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004396 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004397}
4398
4399/// ParseBasicBlock
4400/// ::= LabelStr? Instruction*
4401bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4402 // If this basic block starts out with a name, remember it.
4403 std::string Name;
4404 LocTy NameLoc = Lex.getLoc();
4405 if (Lex.getKind() == lltok::LabelStr) {
4406 Name = Lex.getStrVal();
4407 Lex.Lex();
4408 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004409
Chris Lattnerac161bf2009-01-02 07:01:27 +00004410 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004411 if (!BB)
4412 return Error(NameLoc,
4413 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004414
Chris Lattnerac161bf2009-01-02 07:01:27 +00004415 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004416
Chris Lattnerac161bf2009-01-02 07:01:27 +00004417 // Parse the instructions in this block until we get a terminator.
4418 Instruction *Inst;
4419 do {
4420 // This instruction may have three possibilities for a name: a) none
4421 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4422 LocTy NameLoc = Lex.getLoc();
4423 int NameID = -1;
4424 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004425
Chris Lattnerac161bf2009-01-02 07:01:27 +00004426 if (Lex.getKind() == lltok::LocalVarID) {
4427 NameID = Lex.getUIntVal();
4428 Lex.Lex();
4429 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4430 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004431 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004432 NameStr = Lex.getStrVal();
4433 Lex.Lex();
4434 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4435 return true;
4436 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004437
Chris Lattner77b89dc2009-12-30 05:23:43 +00004438 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004439 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004440 case InstError: return true;
4441 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004442 BB->getInstList().push_back(Inst);
4443
Chris Lattner77b89dc2009-12-30 05:23:43 +00004444 // With a normal result, we check to see if the instruction is followed by
4445 // a comma and metadata.
4446 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004447 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004448 return true;
4449 break;
4450 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004451 BB->getInstList().push_back(Inst);
4452
Chris Lattner77b89dc2009-12-30 05:23:43 +00004453 // If the instruction parser ate an extra comma at the end of it, it
4454 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004455 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004456 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004457 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004458 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004459
Chris Lattnerac161bf2009-01-02 07:01:27 +00004460 // Set the name on the instruction.
4461 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4462 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004463
Chris Lattnerac161bf2009-01-02 07:01:27 +00004464 return false;
4465}
4466
4467//===----------------------------------------------------------------------===//
4468// Instruction Parsing.
4469//===----------------------------------------------------------------------===//
4470
4471/// ParseInstruction - Parse one of the many different instructions.
4472///
Chris Lattner77b89dc2009-12-30 05:23:43 +00004473int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4474 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004475 lltok::Kind Token = Lex.getKind();
4476 if (Token == lltok::Eof)
4477 return TokError("found end of file when expecting more instructions");
4478 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00004479 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004480 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004481
Chris Lattnerac161bf2009-01-02 07:01:27 +00004482 switch (Token) {
4483 default: return Error(Loc, "expected instruction opcode");
4484 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00004485 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004486 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4487 case lltok::kw_br: return ParseBr(Inst, PFS);
4488 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004489 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004490 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004491 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004492 // Binary Operators.
4493 case lltok::kw_add:
4494 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004495 case lltok::kw_mul:
4496 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00004497 bool NUW = EatIfPresent(lltok::kw_nuw);
4498 bool NSW = EatIfPresent(lltok::kw_nsw);
4499 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004500
Chris Lattnera676c0f2011-02-07 16:40:21 +00004501 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004502
Chris Lattnera676c0f2011-02-07 16:40:21 +00004503 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4504 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4505 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004506 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004507 case lltok::kw_fadd:
4508 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00004509 case lltok::kw_fmul:
4510 case lltok::kw_fdiv:
4511 case lltok::kw_frem: {
4512 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4513 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4514 if (Res != 0)
4515 return Res;
4516 if (FMF.any())
4517 Inst->setFastMathFlags(FMF);
4518 return 0;
4519 }
Dan Gohmana5b96452009-06-04 22:49:04 +00004520
Chris Lattner35315d02011-02-06 21:44:57 +00004521 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00004522 case lltok::kw_udiv:
4523 case lltok::kw_lshr:
4524 case lltok::kw_ashr: {
4525 bool Exact = EatIfPresent(lltok::kw_exact);
4526
4527 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4528 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4529 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00004530 }
4531
Chris Lattnerac161bf2009-01-02 07:01:27 +00004532 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00004533 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004534 case lltok::kw_and:
4535 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00004536 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004537 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004538 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004539 // Casts.
4540 case lltok::kw_trunc:
4541 case lltok::kw_zext:
4542 case lltok::kw_sext:
4543 case lltok::kw_fptrunc:
4544 case lltok::kw_fpext:
4545 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004546 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004547 case lltok::kw_uitofp:
4548 case lltok::kw_sitofp:
4549 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004550 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004551 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00004552 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004553 // Other.
4554 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00004555 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004556 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4557 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4558 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4559 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00004560 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00004561 // Call.
4562 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4563 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4564 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004565 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00004566 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00004567 case lltok::kw_load: return ParseLoad(Inst, PFS);
4568 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00004569 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4570 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004571 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004572 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4573 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4574 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4575 }
4576}
4577
4578/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4579bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004580 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004581 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004582 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004583 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4584 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4585 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4586 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4587 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4588 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4589 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4590 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4591 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4592 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4593 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4594 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4595 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4596 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4597 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4598 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4599 }
4600 } else {
4601 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00004602 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004603 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4604 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4605 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4606 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4607 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4608 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4609 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4610 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4611 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4612 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4613 }
4614 }
4615 Lex.Lex();
4616 return false;
4617}
4618
4619//===----------------------------------------------------------------------===//
4620// Terminator Instructions.
4621//===----------------------------------------------------------------------===//
4622
4623/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00004624/// ::= 'ret' void (',' !dbg, !1)*
4625/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00004626bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004627 PerFunctionState &PFS) {
4628 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00004629 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00004630 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004631
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004632 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004633
Chris Lattnerfdd87902009-10-05 05:54:46 +00004634 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004635 if (!ResType->isVoidTy())
4636 return Error(TypeLoc, "value doesn't match function result type '" +
4637 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004638
Owen Anderson55f1c092009-08-13 21:58:54 +00004639 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004640 return false;
4641 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004642
Chris Lattnerac161bf2009-01-02 07:01:27 +00004643 Value *RV;
4644 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004645
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004646 if (ResType != RV->getType())
4647 return Error(TypeLoc, "value doesn't match function result type '" +
4648 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004649
Owen Anderson55f1c092009-08-13 21:58:54 +00004650 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00004651 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004652}
4653
4654
4655/// ParseBr
4656/// ::= 'br' TypeAndValue
4657/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4658bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4659 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004660 Value *Op0;
4661 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004662 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004663
Chris Lattnerac161bf2009-01-02 07:01:27 +00004664 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4665 Inst = BranchInst::Create(BB);
4666 return false;
4667 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004668
Owen Anderson55f1c092009-08-13 21:58:54 +00004669 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004670 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004671
Chris Lattnerac161bf2009-01-02 07:01:27 +00004672 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004673 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004674 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004675 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004676 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004677
Chris Lattner3ed871f2009-10-27 19:13:16 +00004678 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004679 return false;
4680}
4681
4682/// ParseSwitch
4683/// Instruction
4684/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4685/// JumpTable
4686/// ::= (TypeAndValue ',' TypeAndValue)*
4687bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4688 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00004689 Value *Cond;
4690 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004691 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4692 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004693 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004694 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4695 return true;
4696
Duncan Sands19d0b472010-02-16 11:11:14 +00004697 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004698 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004699
Chris Lattnerac161bf2009-01-02 07:01:27 +00004700 // Parse the jump table pairs.
4701 SmallPtrSet<Value*, 32> SeenCases;
4702 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4703 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004704 Value *Constant;
4705 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004706
Chris Lattnerac161bf2009-01-02 07:01:27 +00004707 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4708 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004709 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004710 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004711
David Blaikie70573dc2014-11-19 07:49:26 +00004712 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004713 return Error(CondLoc, "duplicate case value in switch");
4714 if (!isa<ConstantInt>(Constant))
4715 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004716
Chris Lattner3ed871f2009-10-27 19:13:16 +00004717 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004718 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004719
Chris Lattnerac161bf2009-01-02 07:01:27 +00004720 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004721
Chris Lattner3ed871f2009-10-27 19:13:16 +00004722 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004723 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4724 SI->addCase(Table[i].first, Table[i].second);
4725 Inst = SI;
4726 return false;
4727}
4728
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004729/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00004730/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004731/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4732bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00004733 LocTy AddrLoc;
4734 Value *Address;
4735 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004736 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4737 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00004738 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004739
Duncan Sands19d0b472010-02-16 11:11:14 +00004740 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004741 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004742
Chris Lattner3ed871f2009-10-27 19:13:16 +00004743 // Parse the destination list.
4744 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004745
Chris Lattner3ed871f2009-10-27 19:13:16 +00004746 if (Lex.getKind() != lltok::rsquare) {
4747 BasicBlock *DestBB;
4748 if (ParseTypeAndBasicBlock(DestBB, PFS))
4749 return true;
4750 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004751
Chris Lattner3ed871f2009-10-27 19:13:16 +00004752 while (EatIfPresent(lltok::comma)) {
4753 if (ParseTypeAndBasicBlock(DestBB, PFS))
4754 return true;
4755 DestList.push_back(DestBB);
4756 }
4757 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004758
Chris Lattner3ed871f2009-10-27 19:13:16 +00004759 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4760 return true;
4761
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004762 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00004763 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4764 IBI->addDestination(DestList[i]);
4765 Inst = IBI;
4766 return false;
4767}
4768
4769
Chris Lattnerac161bf2009-01-02 07:01:27 +00004770/// ParseInvoke
4771/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4772/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4773bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4774 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00004775 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004776 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00004777 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004778 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00004779 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004780 LocTy RetTypeLoc;
4781 ValID CalleeID;
4782 SmallVector<ParamInfo, 16> ArgList;
4783
Chris Lattner3ed871f2009-10-27 19:13:16 +00004784 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004785 if (ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00004786 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004787 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004788 ParseValID(CalleeID) ||
4789 ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004790 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4791 NoBuiltinLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004792 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004793 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004794 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00004795 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004796 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004797
Chris Lattnerac161bf2009-01-02 07:01:27 +00004798 // If RetType is a non-function pointer type, then this is the short syntax
4799 // for the call, which means that RetType is just the return type. Infer the
4800 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00004801 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4802 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004803 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00004804 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004805 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4806 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004807
Chris Lattnerac161bf2009-01-02 07:01:27 +00004808 if (!FunctionType::isValidReturnType(RetType))
4809 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004810
Owen Anderson4056ca92009-07-29 22:17:13 +00004811 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004812 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004813
Chris Lattnerac161bf2009-01-02 07:01:27 +00004814 // Look up the callee.
4815 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00004816 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4817 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004818
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004819 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00004820 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004821 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004822 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4823 AttributeSet::ReturnIndex,
4824 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004825
Chris Lattnerac161bf2009-01-02 07:01:27 +00004826 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004827
Chris Lattnerac161bf2009-01-02 07:01:27 +00004828 // Loop through FunctionType's arguments and ensure they are specified
4829 // correctly. Also, gather any parameter attributes.
4830 FunctionType::param_iterator I = Ty->param_begin();
4831 FunctionType::param_iterator E = Ty->param_end();
4832 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004833 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004834 if (I != E) {
4835 ExpectedTy = *I++;
4836 } else if (!Ty->isVarArg()) {
4837 return Error(ArgList[i].Loc, "too many arguments specified");
4838 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004839
Chris Lattnerac161bf2009-01-02 07:01:27 +00004840 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4841 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004842 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004843 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004844 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4845 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004846 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4847 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004848 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004849
Chris Lattnerac161bf2009-01-02 07:01:27 +00004850 if (I != E)
4851 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004852
David Majnemer8d22abd2015-02-23 00:01:32 +00004853 if (FnAttrs.hasAttributes()) {
4854 if (FnAttrs.hasAlignmentAttr())
4855 return Error(CallLoc, "invoke instructions may not have an alignment");
4856
Bill Wendlingf5075a42013-01-27 02:24:02 +00004857 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4858 AttributeSet::FunctionIndex,
4859 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00004860 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004861
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004862 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00004863 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004864
David Blaikie3e807092015-05-13 18:35:26 +00004865 InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004866 II->setCallingConv(CC);
4867 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004868 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004869 Inst = II;
4870 return false;
4871}
4872
Bill Wendlingf891bf82011-07-31 06:30:59 +00004873/// ParseResume
4874/// ::= 'resume' TypeAndValue
4875bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4876 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004877 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4878 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004879
Bill Wendlingf891bf82011-07-31 06:30:59 +00004880 ResumeInst *RI = ResumeInst::Create(Exn);
4881 Inst = RI;
4882 return false;
4883}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004884
4885//===----------------------------------------------------------------------===//
4886// Binary Operators.
4887//===----------------------------------------------------------------------===//
4888
4889/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004890/// ::= ArithmeticOps TypeAndValue ',' Value
4891///
4892/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4893/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00004894bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004895 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004896 LocTy Loc; Value *LHS, *RHS;
4897 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4898 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4899 ParseValue(LHS->getType(), RHS, PFS))
4900 return true;
4901
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004902 bool Valid;
4903 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00004904 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004905 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00004906 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4907 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004908 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00004909 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4910 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004911 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004912
Chris Lattnereeefa9a2009-01-05 08:24:46 +00004913 if (!Valid)
4914 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004915
Chris Lattnerac161bf2009-01-02 07:01:27 +00004916 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4917 return false;
4918}
4919
4920/// ParseLogical
4921/// ::= ArithmeticOps TypeAndValue ',' Value {
4922bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4923 unsigned Opc) {
4924 LocTy Loc; Value *LHS, *RHS;
4925 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4926 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4927 ParseValue(LHS->getType(), RHS, PFS))
4928 return true;
4929
Duncan Sands9dff9be2010-02-15 16:12:20 +00004930 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004931 return Error(Loc,"instruction requires integer or integer vector operands");
4932
4933 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4934 return false;
4935}
4936
4937
4938/// ParseCompare
4939/// ::= 'icmp' IPredicates TypeAndValue ',' Value
4940/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00004941bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4942 unsigned Opc) {
4943 // Parse the integer/fp comparison predicate.
4944 LocTy Loc;
4945 unsigned Pred;
4946 Value *LHS, *RHS;
4947 if (ParseCmpPredicate(Pred, Opc) ||
4948 ParseTypeAndValue(LHS, Loc, PFS) ||
4949 ParseToken(lltok::comma, "expected ',' after compare value") ||
4950 ParseValue(LHS->getType(), RHS, PFS))
4951 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004952
Chris Lattnerac161bf2009-01-02 07:01:27 +00004953 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00004954 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004955 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004956 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004957 } else {
4958 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00004959 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00004960 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004961 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00004962 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004963 }
4964 return false;
4965}
4966
4967//===----------------------------------------------------------------------===//
4968// Other Instructions.
4969//===----------------------------------------------------------------------===//
4970
4971
4972/// ParseCast
4973/// ::= CastOpc TypeAndValue 'to' Type
4974bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4975 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004976 LocTy Loc;
4977 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00004978 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004979 if (ParseTypeAndValue(Op, Loc, PFS) ||
4980 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4981 ParseType(DestTy))
4982 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004983
Chris Lattner89d856e2009-03-01 00:53:13 +00004984 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4985 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004986 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004987 getTypeString(Op->getType()) + "' to '" +
4988 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00004989 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004990 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4991 return false;
4992}
4993
4994/// ParseSelect
4995/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4996bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4997 LocTy Loc;
4998 Value *Op0, *Op1, *Op2;
4999 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5000 ParseToken(lltok::comma, "expected ',' after select condition") ||
5001 ParseTypeAndValue(Op1, PFS) ||
5002 ParseToken(lltok::comma, "expected ',' after select value") ||
5003 ParseTypeAndValue(Op2, PFS))
5004 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005005
Chris Lattnerac161bf2009-01-02 07:01:27 +00005006 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5007 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005008
Chris Lattnerac161bf2009-01-02 07:01:27 +00005009 Inst = SelectInst::Create(Op0, Op1, Op2);
5010 return false;
5011}
5012
Chris Lattnerb55ab542009-01-05 08:18:44 +00005013/// ParseVA_Arg
5014/// ::= 'va_arg' TypeAndValue ',' Type
5015bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005016 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005017 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005018 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005019 if (ParseTypeAndValue(Op, PFS) ||
5020 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005021 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005022 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005023
Chris Lattnerb55ab542009-01-05 08:18:44 +00005024 if (!EltTy->isFirstClassType())
5025 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005026
5027 Inst = new VAArgInst(Op, EltTy);
5028 return false;
5029}
5030
5031/// ParseExtractElement
5032/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5033bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5034 LocTy Loc;
5035 Value *Op0, *Op1;
5036 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5037 ParseToken(lltok::comma, "expected ',' after extract value") ||
5038 ParseTypeAndValue(Op1, PFS))
5039 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005040
Chris Lattnerac161bf2009-01-02 07:01:27 +00005041 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5042 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005043
Eric Christopherc9742252009-07-25 02:28:41 +00005044 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005045 return false;
5046}
5047
5048/// ParseInsertElement
5049/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5050bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5051 LocTy Loc;
5052 Value *Op0, *Op1, *Op2;
5053 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5054 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5055 ParseTypeAndValue(Op1, PFS) ||
5056 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5057 ParseTypeAndValue(Op2, PFS))
5058 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005059
Chris Lattnerac161bf2009-01-02 07:01:27 +00005060 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005061 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005062
Chris Lattnerac161bf2009-01-02 07:01:27 +00005063 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5064 return false;
5065}
5066
5067/// ParseShuffleVector
5068/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5069bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5070 LocTy Loc;
5071 Value *Op0, *Op1, *Op2;
5072 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5073 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5074 ParseTypeAndValue(Op1, PFS) ||
5075 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5076 ParseTypeAndValue(Op2, PFS))
5077 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005078
Chris Lattnerac161bf2009-01-02 07:01:27 +00005079 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005080 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005081
Chris Lattnerac161bf2009-01-02 07:01:27 +00005082 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5083 return false;
5084}
5085
5086/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005087/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005088int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005089 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005090 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005091
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005092 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005093 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5094 ParseValue(Ty, Op0, PFS) ||
5095 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005096 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005097 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5098 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005099
Chris Lattnerf4f03422009-12-30 05:27:33 +00005100 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005101 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5102 while (1) {
5103 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005104
Chris Lattner3822f632009-01-02 08:05:26 +00005105 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005106 break;
5107
Chris Lattnerf4f03422009-12-30 05:27:33 +00005108 if (Lex.getKind() == lltok::MetadataVar) {
5109 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005110 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005111 }
Devang Patel8f842d32009-10-16 18:45:49 +00005112
Chris Lattner3822f632009-01-02 08:05:26 +00005113 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005114 ParseValue(Ty, Op0, PFS) ||
5115 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005116 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005117 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5118 return true;
5119 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005120
Chris Lattnerac161bf2009-01-02 07:01:27 +00005121 if (!Ty->isFirstClassType())
5122 return Error(TypeLoc, "phi node must have first class type");
5123
Jay Foad52131342011-03-30 11:28:46 +00005124 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005125 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5126 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5127 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005128 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005129}
5130
Bill Wendlingfae14752011-08-12 20:24:12 +00005131/// ParseLandingPad
5132/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5133/// Clause
5134/// ::= 'catch' TypeAndValue
5135/// ::= 'filter'
5136/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5137bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005138 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005139
David Majnemer7fddecc2015-06-17 20:52:32 +00005140 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005141 return true;
5142
David Majnemer7fddecc2015-06-17 20:52:32 +00005143 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005144 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5145
5146 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5147 LandingPadInst::ClauseType CT;
5148 if (EatIfPresent(lltok::kw_catch))
5149 CT = LandingPadInst::Catch;
5150 else if (EatIfPresent(lltok::kw_filter))
5151 CT = LandingPadInst::Filter;
5152 else
5153 return TokError("expected 'catch' or 'filter' clause type");
5154
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005155 Value *V;
5156 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005157 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005158 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005159
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005160 // A 'catch' type expects a non-array constant. A filter clause expects an
5161 // array constant.
5162 if (CT == LandingPadInst::Catch) {
5163 if (isa<ArrayType>(V->getType()))
5164 Error(VLoc, "'catch' clause has an invalid type");
5165 } else {
5166 if (!isa<ArrayType>(V->getType()))
5167 Error(VLoc, "'filter' clause has an invalid type");
5168 }
5169
Owen Andersonf8f259d2015-03-09 07:13:42 +00005170 Constant *CV = dyn_cast<Constant>(V);
5171 if (!CV)
5172 return Error(VLoc, "clause argument must be a constant");
5173 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005174 }
5175
Owen Andersonf8f259d2015-03-09 07:13:42 +00005176 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005177 return false;
5178}
5179
Chris Lattnerac161bf2009-01-02 07:01:27 +00005180/// ParseCall
Reid Kleckner5772b772014-04-24 20:14:34 +00005181/// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5182/// ParameterList OptionalAttrs
5183/// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5184/// ParameterList OptionalAttrs
5185/// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005186/// ParameterList OptionalAttrs
5187bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005188 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005189 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005190 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005191 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005192 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005193 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005194 LocTy RetTypeLoc;
5195 ValID CalleeID;
5196 SmallVector<ParamInfo, 16> ArgList;
5197 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005198
Reid Kleckner5772b772014-04-24 20:14:34 +00005199 if ((TCK != CallInst::TCK_None &&
5200 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005201 ParseOptionalCallingConv(CC) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00005202 ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005203 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005204 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005205 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5206 PFS.getFunction().isVarArg()) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005207 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00005208 BuiltinLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005209 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005210
Chris Lattnerac161bf2009-01-02 07:01:27 +00005211 // If RetType is a non-function pointer type, then this is the short syntax
5212 // for the call, which means that RetType is just the return type. Infer the
5213 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005214 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5215 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005216 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005217 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005218 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5219 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005220
Chris Lattnerac161bf2009-01-02 07:01:27 +00005221 if (!FunctionType::isValidReturnType(RetType))
5222 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005223
Owen Anderson4056ca92009-07-29 22:17:13 +00005224 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005225 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005226
Chris Lattnerac161bf2009-01-02 07:01:27 +00005227 // Look up the callee.
5228 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005229 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5230 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005231
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005232 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005233 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005234 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005235 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5236 AttributeSet::ReturnIndex,
5237 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005238
Chris Lattnerac161bf2009-01-02 07:01:27 +00005239 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005240
Chris Lattnerac161bf2009-01-02 07:01:27 +00005241 // Loop through FunctionType's arguments and ensure they are specified
5242 // correctly. Also, gather any parameter attributes.
5243 FunctionType::param_iterator I = Ty->param_begin();
5244 FunctionType::param_iterator E = Ty->param_end();
5245 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005246 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005247 if (I != E) {
5248 ExpectedTy = *I++;
5249 } else if (!Ty->isVarArg()) {
5250 return Error(ArgList[i].Loc, "too many arguments specified");
5251 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005252
Chris Lattnerac161bf2009-01-02 07:01:27 +00005253 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5254 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005255 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005256 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005257 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5258 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005259 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5260 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005261 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005262
Chris Lattnerac161bf2009-01-02 07:01:27 +00005263 if (I != E)
5264 return Error(CallLoc, "not enough parameters specified for call");
5265
David Majnemer8d22abd2015-02-23 00:01:32 +00005266 if (FnAttrs.hasAttributes()) {
5267 if (FnAttrs.hasAlignmentAttr())
5268 return Error(CallLoc, "call instructions may not have an alignment");
5269
Bill Wendlingf5075a42013-01-27 02:24:02 +00005270 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5271 AttributeSet::FunctionIndex,
5272 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005273 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005274
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005275 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005276 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005277
David Blaikie348de692015-04-23 21:36:23 +00005278 CallInst *CI = CallInst::Create(Ty, Callee, Args);
Reid Kleckner5772b772014-04-24 20:14:34 +00005279 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005280 CI->setCallingConv(CC);
5281 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005282 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005283 Inst = CI;
5284 return false;
5285}
5286
5287//===----------------------------------------------------------------------===//
5288// Memory Instructions.
5289//===----------------------------------------------------------------------===//
5290
5291/// ParseAlloc
David Majnemerc4ab61c2014-03-09 06:41:58 +00005292/// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00005293int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005294 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00005295 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005296 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005297 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00005298
5299 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5300
David Majnemera3b0eb22015-02-16 08:38:03 +00005301 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005302
David Majnemera3b0eb22015-02-16 08:38:03 +00005303 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5304 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00005305
Chris Lattnerb2f39502009-12-30 05:44:30 +00005306 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00005307 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00005308 if (Lex.getKind() == lltok::kw_align) {
5309 if (ParseOptionalAlignment(Alignment)) return true;
5310 } else if (Lex.getKind() == lltok::MetadataVar) {
5311 AteExtraComma = true;
5312 } else {
5313 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5314 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5315 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005316 }
5317 }
5318
Dan Gohman2140a742010-05-28 01:14:11 +00005319 if (Size && !Size->getType()->isIntegerTy())
5320 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005321
Reid Kleckner436c42e2014-01-17 23:58:17 +00005322 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5323 AI->setUsedWithInAlloca(IsInAlloca);
5324 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00005325 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005326}
5327
5328/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00005329/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005330/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00005331/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005332int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005333 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005334 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005335 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005336 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005337 AtomicOrdering Ordering = NotAtomic;
5338 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005339
5340 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005341 isAtomic = true;
5342 Lex.Lex();
5343 }
5344
Chris Lattnerbc639292011-11-27 06:56:53 +00005345 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005346 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005347 isVolatile = true;
5348 Lex.Lex();
5349 }
5350
David Blaikie15d9a4c2015-04-06 20:59:48 +00005351 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00005352 LocTy ExplicitTypeLoc = Lex.getLoc();
5353 if (ParseType(Ty) ||
5354 ParseToken(lltok::comma, "expected comma after load's type") ||
5355 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005356 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005357 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5358 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005359
David Blaikie15d9a4c2015-04-06 20:59:48 +00005360 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005361 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00005362 if (isAtomic && !Alignment)
5363 return Error(Loc, "atomic load must have explicit non-zero alignment");
5364 if (Ordering == Release || Ordering == AcquireRelease)
5365 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005366
David Blaikiea79ac142015-02-27 21:17:42 +00005367 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5368 return Error(ExplicitTypeLoc,
5369 "explicit pointee type doesn't match operand's pointee type");
5370
David Blaikie15d9a4c2015-04-06 20:59:48 +00005371 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005372 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005373}
5374
5375/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00005376
5377/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5378/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00005379/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00005380int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005381 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00005382 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00005383 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005384 bool isAtomic = false;
Eli Friedman59b66882011-08-09 23:02:53 +00005385 AtomicOrdering Ordering = NotAtomic;
5386 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005387
5388 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005389 isAtomic = true;
5390 Lex.Lex();
5391 }
5392
Chris Lattnerbc639292011-11-27 06:56:53 +00005393 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00005394 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00005395 isVolatile = true;
5396 Lex.Lex();
5397 }
5398
Chris Lattnerac161bf2009-01-02 07:01:27 +00005399 if (ParseTypeAndValue(Val, Loc, PFS) ||
5400 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005401 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00005402 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00005403 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005404 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00005405
Duncan Sands19d0b472010-02-16 11:11:14 +00005406 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005407 return Error(PtrLoc, "store operand must be a pointer");
5408 if (!Val->getType()->isFirstClassType())
5409 return Error(Loc, "store operand must be a first class value");
5410 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5411 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00005412 if (isAtomic && !Alignment)
5413 return Error(Loc, "atomic store must have explicit non-zero alignment");
5414 if (Ordering == Acquire || Ordering == AcquireRelease)
5415 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005416
Eli Friedman59b66882011-08-09 23:02:53 +00005417 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00005418 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005419}
5420
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005421/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00005422/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5423/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00005424int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005425 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5426 bool AteExtraComma = false;
Tim Northovere94a5182014-03-11 10:48:52 +00005427 AtomicOrdering SuccessOrdering = NotAtomic;
5428 AtomicOrdering FailureOrdering = NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005429 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005430 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00005431 bool isWeak = false;
5432
5433 if (EatIfPresent(lltok::kw_weak))
5434 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00005435
5436 if (EatIfPresent(lltok::kw_volatile))
5437 isVolatile = true;
5438
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005439 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5440 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5441 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5442 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5443 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00005444 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5445 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005446 return true;
5447
Tim Northovere94a5182014-03-11 10:48:52 +00005448 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005449 return TokError("cmpxchg cannot be unordered");
Tim Northovere94a5182014-03-11 10:48:52 +00005450 if (SuccessOrdering < FailureOrdering)
5451 return TokError("cmpxchg must be at least as ordered on success as failure");
5452 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5453 return TokError("cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005454 if (!Ptr->getType()->isPointerTy())
5455 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5456 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5457 return Error(CmpLoc, "compare value and pointer type do not match");
5458 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5459 return Error(NewLoc, "new value and pointer type do not match");
5460 if (!New->getType()->isIntegerTy())
5461 return Error(NewLoc, "cmpxchg operand must be an integer");
5462 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5463 if (Size < 8 || (Size & (Size - 1)))
5464 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5465 " integer");
5466
Tim Northover420a2162014-06-13 14:24:07 +00005467 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5468 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005469 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00005470 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005471 Inst = CXI;
5472 return AteExtraComma ? InstExtraComma : InstNormal;
5473}
5474
5475/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00005476/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5477/// 'singlethread'? AtomicOrdering
5478int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005479 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5480 bool AteExtraComma = false;
5481 AtomicOrdering Ordering = NotAtomic;
5482 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00005483 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005484 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00005485
5486 if (EatIfPresent(lltok::kw_volatile))
5487 isVolatile = true;
5488
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005489 switch (Lex.getKind()) {
5490 default: return TokError("expected binary operation in atomicrmw");
5491 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5492 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5493 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5494 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5495 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5496 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5497 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5498 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5499 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5500 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5501 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5502 }
5503 Lex.Lex(); // Eat the operation.
5504
5505 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5506 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5507 ParseTypeAndValue(Val, ValLoc, PFS) ||
5508 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5509 return true;
5510
5511 if (Ordering == Unordered)
5512 return TokError("atomicrmw cannot be unordered");
5513 if (!Ptr->getType()->isPointerTy())
5514 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5515 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5516 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5517 if (!Val->getType()->isIntegerTy())
5518 return Error(ValLoc, "atomicrmw operand must be an integer");
5519 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5520 if (Size < 8 || (Size & (Size - 1)))
5521 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5522 " integer");
5523
5524 AtomicRMWInst *RMWI =
5525 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5526 RMWI->setVolatile(isVolatile);
5527 Inst = RMWI;
5528 return AteExtraComma ? InstExtraComma : InstNormal;
5529}
5530
Eli Friedmanfee02c62011-07-25 23:16:38 +00005531/// ParseFence
5532/// ::= 'fence' 'singlethread'? AtomicOrdering
5533int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5534 AtomicOrdering Ordering = NotAtomic;
5535 SynchronizationScope Scope = CrossThread;
5536 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5537 return true;
5538
5539 if (Ordering == Unordered)
5540 return TokError("fence cannot be unordered");
5541 if (Ordering == Monotonic)
5542 return TokError("fence cannot be monotonic");
5543
5544 Inst = new FenceInst(Context, Ordering, Scope);
5545 return InstNormal;
5546}
5547
Chris Lattnerac161bf2009-01-02 07:01:27 +00005548/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00005549/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005550int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005551 Value *Ptr = nullptr;
5552 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005553 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00005554
Dan Gohman16cbbe42009-07-29 15:58:36 +00005555 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00005556
David Blaikie79e6c742015-02-27 19:29:02 +00005557 Type *Ty = nullptr;
5558 LocTy ExplicitTypeLoc = Lex.getLoc();
5559 if (ParseType(Ty) ||
5560 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5561 ParseTypeAndValue(Ptr, Loc, PFS))
5562 return true;
5563
Eli Benderskyd9806682013-04-22 17:03:42 +00005564 Type *BaseType = Ptr->getType();
5565 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5566 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005567 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005568
David Blaikie8d757942015-03-09 23:08:44 +00005569 if (Ty != BasePointerType->getElementType())
5570 return Error(ExplicitTypeLoc,
5571 "explicit pointee type doesn't match operand's pointee type");
5572
Chris Lattnerac161bf2009-01-02 07:01:27 +00005573 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005574 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005575 // GEP returns a vector of pointers if at least one of parameters is a vector.
5576 // All vector parameters should have the same vector width.
5577 unsigned GEPWidth = BaseType->isVectorTy() ?
5578 BaseType->getVectorNumElements() : 0;
5579
Chris Lattner3822f632009-01-02 08:05:26 +00005580 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00005581 if (Lex.getKind() == lltok::MetadataVar) {
5582 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00005583 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005584 }
Chris Lattner3822f632009-01-02 08:05:26 +00005585 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005586 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005587 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005588
Nadav Rotem3924cb02011-12-05 06:29:09 +00005589 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005590 unsigned ValNumEl = Val->getType()->getVectorNumElements();
5591 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00005592 return Error(EltLoc,
5593 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00005594 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00005595 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005596 Indices.push_back(Val);
5597 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005598
Owen Andersone90f9922015-03-10 06:34:57 +00005599 SmallPtrSet<const Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00005600 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00005601 return Error(Loc, "base element of getelementptr must be sized");
5602
David Blaikied33bad32015-04-17 22:32:13 +00005603 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005604 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00005605 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00005606 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00005607 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005608 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005609}
5610
5611/// ParseExtractValue
5612/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005613int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005614 Value *Val; LocTy Loc;
5615 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005616 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005617 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005618 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005619 return true;
5620
Chris Lattner392be582010-02-12 20:49:41 +00005621 if (!Val->getType()->isAggregateType())
5622 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005623
Jay Foad57aa6362011-07-13 10:26:04 +00005624 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005625 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00005626 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005627 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005628}
5629
5630/// ParseInsertValue
5631/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00005632int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005633 Value *Val0, *Val1; LocTy Loc0, Loc1;
5634 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005635 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005636 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5637 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5638 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00005639 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005640 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005641
Chris Lattner392be582010-02-12 20:49:41 +00005642 if (!Val0->getType()->isAggregateType())
5643 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005644
David Majnemer30074532015-02-11 07:43:58 +00005645 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5646 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005647 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00005648 if (IndexedType != Val1->getType())
5649 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5650 getTypeString(Val1->getType()) + "' instead of '" +
5651 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00005652 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00005653 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005654}
Nick Lewycky49f89192009-04-04 07:22:01 +00005655
5656//===----------------------------------------------------------------------===//
5657// Embedded metadata.
5658//===----------------------------------------------------------------------===//
5659
5660/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005661/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005662/// Element
5663/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005664bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00005665 if (ParseToken(lltok::lbrace, "expected '{' here"))
5666 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005667
Dan Gohman1e0213a2010-07-13 19:33:27 +00005668 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005669 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00005670 return false;
5671
Nick Lewycky49f89192009-04-04 07:22:01 +00005672 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005673 // Null is a special case since it is typeless.
5674 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005675 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00005676 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00005677 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005678
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005679 Metadata *MD;
5680 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005681 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00005682 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00005683 } while (EatIfPresent(lltok::comma));
5684
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005685 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00005686}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00005687
5688//===----------------------------------------------------------------------===//
5689// Use-list order directives.
5690//===----------------------------------------------------------------------===//
5691bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5692 SMLoc Loc) {
5693 if (V->use_empty())
5694 return Error(Loc, "value has no uses");
5695
5696 unsigned NumUses = 0;
5697 SmallDenseMap<const Use *, unsigned, 16> Order;
5698 for (const Use &U : V->uses()) {
5699 if (++NumUses > Indexes.size())
5700 break;
5701 Order[&U] = Indexes[NumUses - 1];
5702 }
5703 if (NumUses < 2)
5704 return Error(Loc, "value only has one use");
5705 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5706 return Error(Loc, "wrong number of indexes, expected " +
5707 Twine(std::distance(V->use_begin(), V->use_end())));
5708
5709 V->sortUseList([&](const Use &L, const Use &R) {
5710 return Order.lookup(&L) < Order.lookup(&R);
5711 });
5712 return false;
5713}
5714
5715/// ParseUseListOrderIndexes
5716/// ::= '{' uint32 (',' uint32)+ '}'
5717bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5718 SMLoc Loc = Lex.getLoc();
5719 if (ParseToken(lltok::lbrace, "expected '{' here"))
5720 return true;
5721 if (Lex.getKind() == lltok::rbrace)
5722 return Lex.Error("expected non-empty list of uselistorder indexes");
5723
5724 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5725 // indexes should be distinct numbers in the range [0, size-1], and should
5726 // not be in order.
5727 unsigned Offset = 0;
5728 unsigned Max = 0;
5729 bool IsOrdered = true;
5730 assert(Indexes.empty() && "Expected empty order vector");
5731 do {
5732 unsigned Index;
5733 if (ParseUInt32(Index))
5734 return true;
5735
5736 // Update consistency checks.
5737 Offset += Index - Indexes.size();
5738 Max = std::max(Max, Index);
5739 IsOrdered &= Index == Indexes.size();
5740
5741 Indexes.push_back(Index);
5742 } while (EatIfPresent(lltok::comma));
5743
5744 if (ParseToken(lltok::rbrace, "expected '}' here"))
5745 return true;
5746
5747 if (Indexes.size() < 2)
5748 return Error(Loc, "expected >= 2 uselistorder indexes");
5749 if (Offset != 0 || Max >= Indexes.size())
5750 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5751 if (IsOrdered)
5752 return Error(Loc, "expected uselistorder indexes to change the order");
5753
5754 return false;
5755}
5756
5757/// ParseUseListOrder
5758/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5759bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5760 SMLoc Loc = Lex.getLoc();
5761 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5762 return true;
5763
5764 Value *V;
5765 SmallVector<unsigned, 16> Indexes;
5766 if (ParseTypeAndValue(V, PFS) ||
5767 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5768 ParseUseListOrderIndexes(Indexes))
5769 return true;
5770
5771 return sortUseListOrder(V, Indexes, Loc);
5772}
5773
5774/// ParseUseListOrderBB
5775/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5776bool LLParser::ParseUseListOrderBB() {
5777 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5778 SMLoc Loc = Lex.getLoc();
5779 Lex.Lex();
5780
5781 ValID Fn, Label;
5782 SmallVector<unsigned, 16> Indexes;
5783 if (ParseValID(Fn) ||
5784 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5785 ParseValID(Label) ||
5786 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5787 ParseUseListOrderIndexes(Indexes))
5788 return true;
5789
5790 // Check the function.
5791 GlobalValue *GV;
5792 if (Fn.Kind == ValID::t_GlobalName)
5793 GV = M->getNamedValue(Fn.StrVal);
5794 else if (Fn.Kind == ValID::t_GlobalID)
5795 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5796 else
5797 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5798 if (!GV)
5799 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5800 auto *F = dyn_cast<Function>(GV);
5801 if (!F)
5802 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5803 if (F->isDeclaration())
5804 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5805
5806 // Check the basic block.
5807 if (Label.Kind == ValID::t_LocalID)
5808 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5809 if (Label.Kind != ValID::t_LocalName)
5810 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5811 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5812 if (!V)
5813 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5814 if (!isa<BasicBlock>(V))
5815 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5816
5817 return sortUseListOrder(V, Indexes, Loc);
5818}