blob: b9415a2659088c996c5fdda2012e809b3fc9a5e7 [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"
Eugene Zelenko1804a772016-08-25 00:45:04 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallPtrSet.h"
David Blaikieadbda4b2015-08-03 20:08:41 +000019#include "llvm/ADT/STLExtras.h"
Alex Lorenz8955f7d2015-06-23 17:10:10 +000020#include "llvm/AsmParser/SlotMapping.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000021#include "llvm/IR/Argument.h"
Chandler Carruth91065212014-03-05 10:34:14 +000022#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000023#include "llvm/IR/BasicBlock.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000025#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000027#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalIFunc.h"
31#include "llvm/IR/GlobalObject.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000033#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Instructions.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000035#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000036#include "llvm/IR/LLVMContext.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000037#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Module.h"
39#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000040#include "llvm/IR/Type.h"
41#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/ValueSymbolTable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000043#include "llvm/Support/Casting.h"
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +000044#include "llvm/Support/Dwarf.h"
Torok Edwin56d06592009-07-11 20:10:48 +000045#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000046#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +000047#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerac161bf2009-01-02 07:01:27 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000049#include <algorithm>
50#include <cassert>
51#include <cstring>
52#include <iterator>
53#include <vector>
54
Chris Lattnerac161bf2009-01-02 07:01:27 +000055using namespace llvm;
56
Chris Lattner229907c2011-07-18 04:54:35 +000057static std::string getTypeString(Type *T) {
Alp Tokere69170a2014-06-26 22:52:05 +000058 std::string Result;
59 raw_string_ostream Tmp(Result);
60 Tmp << *T;
61 return Tmp.str();
Chris Lattner0f214eb2011-06-18 21:18:23 +000062}
63
Chris Lattner3822f632009-01-02 08:05:26 +000064/// Run: module ::= toplevelentity*
Chris Lattnerad6f3352009-01-04 20:44:11 +000065bool LLParser::Run() {
Chris Lattner3822f632009-01-02 08:05:26 +000066 // Prime the lexer.
67 Lex.Lex();
68
Mehdi Amini50af49f2016-04-02 03:46:17 +000069 if (Context.shouldDiscardValueNames())
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000070 return Error(
71 Lex.getLoc(),
72 "Can't read textual IR with a Context that discards named Values");
73
Chris Lattnerad6f3352009-01-04 20:44:11 +000074 return ParseTopLevelEntities() ||
75 ValidateEndOfModule();
Chris Lattnerac161bf2009-01-02 07:01:27 +000076}
77
Alex Lorenz1de2acd2015-08-21 21:32:39 +000078bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
Alex Lorenzd2255952015-07-17 22:07:03 +000081 Lex.Lex();
82
83 Type *Ty = nullptr;
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
85 return true;
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
88 return false;
89}
90
Quentin Colombetdafed5d2016-03-08 00:37:07 +000091bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
Quentin Colombet81e72b42016-03-07 22:09:05 +000093 restoreParsingState(Slots);
94 Lex.Lex();
95
Quentin Colombetdafed5d2016-03-08 00:37:07 +000096 Read = 0;
97 SMLoc Start = Lex.getLoc();
Quentin Colombet81e72b42016-03-07 22:09:05 +000098 Ty = nullptr;
99 if (ParseType(Ty))
100 return true;
Quentin Colombetdafed5d2016-03-08 00:37:07 +0000101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
103
Quentin Colombet81e72b42016-03-07 22:09:05 +0000104 return false;
105}
106
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000107void LLParser::restoreParsingState(const SlotMapping *Slots) {
108 if (!Slots)
109 return;
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
113 NamedTypes.insert(
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
118}
119
Chris Lattnerac161bf2009-01-02 07:01:27 +0000120/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121/// module.
122bool LLParser::ValidateEndOfModule() {
Bill Wendlingb32b0412013-02-08 06:32:06 +0000123 // Handle any function attribute group forward references.
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000124 for (const auto &RAG : ForwardRefAttrGroups) {
125 Value *V = RAG.first;
126 const std::vector<unsigned> &Attrs = RAG.second;
Bill Wendlingb32b0412013-02-08 06:32:06 +0000127 AttrBuilder B;
128
Saleem Abdulrasool17995672016-12-27 18:35:22 +0000129 for (const auto &Attr : Attrs)
130 B.merge(NumberedAttrBuilders[Attr]);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000131
132 if (Function *Fn = dyn_cast<Function>(V)) {
133 AttributeSet AS = Fn->getAttributes();
134 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
135 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
136 AS.getFnAttributes());
137
138 FnAttrs.merge(B);
139
140 // If the alignment was parsed as an attribute, move to the alignment
141 // field.
142 if (FnAttrs.hasAlignmentAttr()) {
143 Fn->setAlignment(FnAttrs.getAlignment());
144 FnAttrs.removeAttribute(Attribute::Alignment);
145 }
146
147 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
148 AttributeSet::get(Context,
149 AttributeSet::FunctionIndex,
150 FnAttrs));
151 Fn->setAttributes(AS);
152 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
153 AttributeSet AS = CI->getAttributes();
154 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
155 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
156 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000157 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000158 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
159 AttributeSet::get(Context,
160 AttributeSet::FunctionIndex,
161 FnAttrs));
162 CI->setAttributes(AS);
163 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
164 AttributeSet AS = II->getAttributes();
165 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
166 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
167 AS.getFnAttributes());
Bill Wendling59dce372013-02-12 10:13:06 +0000168 FnAttrs.merge(B);
Bill Wendlingb32b0412013-02-08 06:32:06 +0000169 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
170 AttributeSet::get(Context,
171 AttributeSet::FunctionIndex,
172 FnAttrs));
173 II->setAttributes(AS);
174 } else {
175 llvm_unreachable("invalid object with forward attribute group reference");
176 }
177 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000178
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +0000179 // If there are entries in ForwardRefBlockAddresses at this point, the
180 // function was never defined.
181 if (!ForwardRefBlockAddresses.empty())
182 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
183 "expected function name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000184
David Majnemer19b51052015-02-11 07:43:56 +0000185 for (const auto &NT : NumberedTypes)
186 if (NT.second.second.isValid())
187 return Error(NT.second.second,
188 "use of undefined type '%" + Twine(NT.first) + "'");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000189
190 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
191 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
192 if (I->second.second.isValid())
193 return Error(I->second.second,
194 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000195
David Majnemerdad0a642014-06-27 18:19:56 +0000196 if (!ForwardRefComdats.empty())
197 return Error(ForwardRefComdats.begin()->second,
198 "use of undefined comdat '$" +
199 ForwardRefComdats.begin()->first + "'");
200
Chris Lattnerac161bf2009-01-02 07:01:27 +0000201 if (!ForwardRefVals.empty())
202 return Error(ForwardRefVals.begin()->second.second,
203 "use of undefined value '@" + ForwardRefVals.begin()->first +
204 "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000205
Chris Lattnerac161bf2009-01-02 07:01:27 +0000206 if (!ForwardRefValIDs.empty())
207 return Error(ForwardRefValIDs.begin()->second.second,
208 "use of undefined value '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000209 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000210
Devang Pateld2541152009-07-08 19:23:54 +0000211 if (!ForwardRefMDNodes.empty())
212 return Error(ForwardRefMDNodes.begin()->second.second,
213 "use of undefined metadata '!" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000214 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000215
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000216 // Resolve metadata cycles.
David Majnemer19b51052015-02-11 07:43:56 +0000217 for (auto &N : NumberedMetadata) {
218 if (N.second && !N.second->isResolved())
219 N.second->resolveCycles();
220 }
Devang Pateld2541152009-07-08 19:23:54 +0000221
Mehdi Aminie4709272016-09-14 22:29:59 +0000222 for (auto *Inst : InstsWithTBAATag) {
223 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
224 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
225 auto *UpgradedMD = UpgradeTBAANode(*MD);
226 if (MD != UpgradedMD)
227 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
228 }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000229
Chris Lattnerac161bf2009-01-02 07:01:27 +0000230 // Look for intrinsic functions and CallInst that need to be upgraded
231 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +0000232 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000233
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000234 // Some types could be renamed during loading if several modules are
235 // loaded in the same LLVMContext (LTO scenario). In this case we should
236 // remangle intrinsics names as well.
237 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
238 Function *F = &*FI++;
239 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
240 F->replaceAllUsesWith(Remangled.getValue());
241 F->eraseFromParent();
242 }
243 }
244
Manman Ren8b4306c2013-12-02 21:29:56 +0000245 UpgradeDebugInfo(*M);
246
Manman Renb5d7ff42016-05-25 23:14:48 +0000247 UpgradeModuleFlags(*M);
248
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000249 if (!Slots)
250 return false;
251 // Initialize the slot mapping.
252 // Because by this point we've parsed and validated everything, we can "steal"
253 // the mapping from LLParser as it doesn't need it anymore.
254 Slots->GlobalValues = std::move(NumberedVals);
255 Slots->MetadataNodes = std::move(NumberedMetadata);
Alex Lorenz1de2acd2015-08-21 21:32:39 +0000256 for (const auto &I : NamedTypes)
257 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
258 for (const auto &I : NumberedTypes)
259 Slots->Types.insert(std::make_pair(I.first, I.second.first));
Alex Lorenz8955f7d2015-06-23 17:10:10 +0000260
Chris Lattnerac161bf2009-01-02 07:01:27 +0000261 return false;
262}
263
264//===----------------------------------------------------------------------===//
265// Top-Level Entities
266//===----------------------------------------------------------------------===//
267
268bool LLParser::ParseTopLevelEntities() {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000269 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000270 switch (Lex.getKind()) {
271 default: return TokError("expected top-level entity");
272 case lltok::Eof: return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000273 case lltok::kw_declare: if (ParseDeclare()) return true; break;
274 case lltok::kw_define: if (ParseDefine()) return true; break;
275 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
276 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
Teresa Johnson83c517c2016-03-30 18:15:08 +0000277 case lltok::kw_source_filename:
278 if (ParseSourceFileName())
279 return true;
280 break;
Bill Wendling706d3d62012-11-28 08:41:48 +0000281 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000282 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000283 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman466876b2009-08-12 23:32:33 +0000284 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000285 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
David Majnemerdad0a642014-06-27 18:19:56 +0000286 case lltok::ComdatVar: if (parseComdat()) return true; break;
Chris Lattner1eed2d62009-12-30 04:56:59 +0000287 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Bill Wendling63b88192013-02-06 06:52:58 +0000288 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
Bill Wendlinga7c38772013-02-09 15:48:49 +0000289 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000290 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
291 case lltok::kw_uselistorder_bb:
Davide Italianof4e16612016-08-26 18:05:03 +0000292 if (ParseUseListOrderBB())
293 return true;
294 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000295 }
296 }
297}
298
Chris Lattnerac161bf2009-01-02 07:01:27 +0000299/// toplevelentity
300/// ::= 'module' 'asm' STRINGCONSTANT
301bool LLParser::ParseModuleAsm() {
302 assert(Lex.getKind() == lltok::kw_module);
303 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000304
305 std::string AsmStr;
Chris Lattner3822f632009-01-02 08:05:26 +0000306 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
307 ParseStringConstant(AsmStr)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000308
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000309 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000310 return false;
311}
312
313/// toplevelentity
314/// ::= 'target' 'triple' '=' STRINGCONSTANT
315/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
316bool LLParser::ParseTargetDefinition() {
317 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3822f632009-01-02 08:05:26 +0000318 std::string Str;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000319 switch (Lex.Lex()) {
320 default: return TokError("unknown target property");
321 case lltok::kw_triple:
322 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000323 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
324 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000325 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000326 M->setTargetTriple(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000327 return false;
328 case lltok::kw_datalayout:
329 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +0000330 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
331 ParseStringConstant(Str))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000332 return true;
Chris Lattner3822f632009-01-02 08:05:26 +0000333 M->setDataLayout(Str);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000334 return false;
335 }
336}
337
Bill Wendling706d3d62012-11-28 08:41:48 +0000338/// toplevelentity
Teresa Johnson83c517c2016-03-30 18:15:08 +0000339/// ::= 'source_filename' '=' STRINGCONSTANT
340bool LLParser::ParseSourceFileName() {
341 assert(Lex.getKind() == lltok::kw_source_filename);
342 std::string Str;
343 Lex.Lex();
344 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
345 ParseStringConstant(Str))
346 return true;
347 M->setSourceFileName(Str);
348 return false;
349}
350
351/// toplevelentity
Bill Wendling706d3d62012-11-28 08:41:48 +0000352/// ::= 'deplibs' '=' '[' ']'
353/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
354/// FIXME: Remove in 4.0. Currently parse, but ignore.
355bool LLParser::ParseDepLibs() {
356 assert(Lex.getKind() == lltok::kw_deplibs);
357 Lex.Lex();
358 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
359 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
360 return true;
361
362 if (EatIfPresent(lltok::rsquare))
363 return false;
364
365 do {
366 std::string Str;
367 if (ParseStringConstant(Str)) return true;
368 } while (EatIfPresent(lltok::comma));
369
370 return ParseToken(lltok::rsquare, "expected ']' at end of list");
371}
372
Dan Gohman466876b2009-08-12 23:32:33 +0000373/// ParseUnnamedType:
Dan Gohman466876b2009-08-12 23:32:33 +0000374/// ::= LocalVarID '=' 'type' type
Chris Lattnerac161bf2009-01-02 07:01:27 +0000375bool LLParser::ParseUnnamedType() {
Chris Lattner07037362011-06-18 23:51:31 +0000376 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000377 unsigned TypeID = Lex.getUIntVal();
Chris Lattner8936d2b2011-06-19 00:03:46 +0000378 Lex.Lex(); // eat LocalVarID;
379
380 if (ParseToken(lltok::equal, "expected '=' after name") ||
381 ParseToken(lltok::kw_type, "expected 'type' after '='"))
382 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000383
Craig Topper2617dcc2014-04-15 06:32:26 +0000384 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000385 if (ParseStructDefinition(TypeLoc, "",
386 NumberedTypes[TypeID], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000387
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000388 if (!isa<StructType>(Result)) {
389 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
390 if (Entry.first)
391 return Error(TypeLoc, "non-struct types may not be recursive");
392 Entry.first = Result;
393 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000394 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000395
Chris Lattnerac161bf2009-01-02 07:01:27 +0000396 return false;
397}
398
399/// toplevelentity
400/// ::= LocalVar '=' 'type' type
401bool LLParser::ParseNamedType() {
402 std::string Name = Lex.getStrVal();
403 LocTy NameLoc = Lex.getLoc();
Chris Lattner3822f632009-01-02 08:05:26 +0000404 Lex.Lex(); // eat LocalVar.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000405
Chris Lattner3822f632009-01-02 08:05:26 +0000406 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000407 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3822f632009-01-02 08:05:26 +0000408 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000409
Craig Topper2617dcc2014-04-15 06:32:26 +0000410 Type *Result = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000411 if (ParseStructDefinition(NameLoc, Name,
412 NamedTypes[Name], Result)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000413
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000414 if (!isa<StructType>(Result)) {
415 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
416 if (Entry.first)
417 return Error(NameLoc, "non-struct types may not be recursive");
418 Entry.first = Result;
419 Entry.second = SMLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000420 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000421
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000422 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000423}
424
Chris Lattnerac161bf2009-01-02 07:01:27 +0000425/// toplevelentity
426/// ::= 'declare' FunctionHeader
427bool LLParser::ParseDeclare() {
428 assert(Lex.getKind() == lltok::kw_declare);
429 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000430
Peter Collingbourne21521892016-06-21 23:42:48 +0000431 std::vector<std::pair<unsigned, MDNode *>> MDs;
432 while (Lex.getKind() == lltok::MetadataVar) {
433 unsigned MDK;
434 MDNode *N;
435 if (ParseMetadataAttachment(MDK, N))
436 return true;
437 MDs.push_back({MDK, N});
438 }
439
Chris Lattnerac161bf2009-01-02 07:01:27 +0000440 Function *F;
Peter Collingbourne21521892016-06-21 23:42:48 +0000441 if (ParseFunctionHeader(F, false))
442 return true;
443 for (auto &MD : MDs)
444 F->addMetadata(MD.first, *MD.second);
445 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000446}
447
448/// toplevelentity
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000449/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
Chris Lattnerac161bf2009-01-02 07:01:27 +0000450bool LLParser::ParseDefine() {
451 assert(Lex.getKind() == lltok::kw_define);
452 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000453
Chris Lattnerac161bf2009-01-02 07:01:27 +0000454 Function *F;
Chris Lattner3822f632009-01-02 08:05:26 +0000455 return ParseFunctionHeader(F, true) ||
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000456 ParseOptionalFunctionMetadata(*F) ||
Chris Lattner3822f632009-01-02 08:05:26 +0000457 ParseFunctionBody(*F);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000458}
459
Chris Lattner3822f632009-01-02 08:05:26 +0000460/// ParseGlobalType
461/// ::= 'constant'
462/// ::= 'global'
Chris Lattnerac161bf2009-01-02 07:01:27 +0000463bool LLParser::ParseGlobalType(bool &IsConstant) {
464 if (Lex.getKind() == lltok::kw_constant)
465 IsConstant = true;
466 else if (Lex.getKind() == lltok::kw_global)
467 IsConstant = false;
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000468 else {
469 IsConstant = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000470 return TokError("expected 'global' or 'constant'");
Duncan Sandsd1de45a2009-02-10 16:24:55 +0000471 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000472 Lex.Lex();
473 return false;
474}
475
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000476bool LLParser::ParseOptionalUnnamedAddr(
477 GlobalVariable::UnnamedAddr &UnnamedAddr) {
478 if (EatIfPresent(lltok::kw_unnamed_addr))
479 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
480 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
481 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
482 else
483 UnnamedAddr = GlobalValue::UnnamedAddr::None;
484 return false;
485}
486
Dan Gohman466876b2009-08-12 23:32:33 +0000487/// ParseUnnamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000488/// OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000489/// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
490/// ... -> global variable
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000491/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000492/// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
493/// ... -> global variable
Dan Gohman466876b2009-08-12 23:32:33 +0000494bool LLParser::ParseUnnamedGlobal() {
495 unsigned VarID = NumberedVals.size();
496 std::string Name;
497 LocTy NameLoc = Lex.getLoc();
498
499 // Handle the GlobalID form.
500 if (Lex.getKind() == lltok::GlobalID) {
501 if (Lex.getUIntVal() != VarID)
502 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +0000503 Twine(VarID) + "'");
Dan Gohman466876b2009-08-12 23:32:33 +0000504 Lex.Lex(); // eat GlobalID;
505
506 if (ParseToken(lltok::equal, "expected '=' after name"))
507 return true;
508 }
509
510 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000511 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000512 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000513 GlobalVariable::UnnamedAddr UnnamedAddr;
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000514 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000515 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Dan Gohman466876b2009-08-12 23:32:33 +0000516 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000517
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000518 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000519 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000520 DLLStorageClass, TLM, UnnamedAddr);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000521
522 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
523 DLLStorageClass, TLM, UnnamedAddr);
Dan Gohman466876b2009-08-12 23:32:33 +0000524}
525
Chris Lattnerac161bf2009-01-02 07:01:27 +0000526/// ParseNamedGlobal:
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000527/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
Nico Rieck7157bb72014-01-14 15:22:47 +0000528/// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
529/// ... -> global variable
Chris Lattnerac161bf2009-01-02 07:01:27 +0000530bool LLParser::ParseNamedGlobal() {
531 assert(Lex.getKind() == lltok::GlobalVar);
532 LocTy NameLoc = Lex.getLoc();
533 std::string Name = Lex.getStrVal();
534 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000535
Chris Lattnerac161bf2009-01-02 07:01:27 +0000536 bool HasLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000537 unsigned Linkage, Visibility, DLLStorageClass;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000538 GlobalVariable::ThreadLocalMode TLM;
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000539 GlobalVariable::UnnamedAddr UnnamedAddr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000540 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
Rafael Espindola2615c9e2016-05-12 12:37:52 +0000541 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000542 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
Chris Lattnerac161bf2009-01-02 07:01:27 +0000543 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000544
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000545 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
Nico Rieck7157bb72014-01-14 15:22:47 +0000546 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000547 DLLStorageClass, TLM, UnnamedAddr);
Rafael Espindola464fe022014-07-30 22:51:54 +0000548
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000549 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
550 DLLStorageClass, TLM, UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000551}
552
David Majnemerdad0a642014-06-27 18:19:56 +0000553bool LLParser::parseComdat() {
554 assert(Lex.getKind() == lltok::ComdatVar);
555 std::string Name = Lex.getStrVal();
556 LocTy NameLoc = Lex.getLoc();
557 Lex.Lex();
558
559 if (ParseToken(lltok::equal, "expected '=' here"))
560 return true;
561
562 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
563 return TokError("expected comdat type");
564
565 Comdat::SelectionKind SK;
566 switch (Lex.getKind()) {
567 default:
568 return TokError("unknown selection kind");
569 case lltok::kw_any:
570 SK = Comdat::Any;
571 break;
572 case lltok::kw_exactmatch:
573 SK = Comdat::ExactMatch;
574 break;
575 case lltok::kw_largest:
576 SK = Comdat::Largest;
577 break;
578 case lltok::kw_noduplicates:
579 SK = Comdat::NoDuplicates;
580 break;
581 case lltok::kw_samesize:
582 SK = Comdat::SameSize;
583 break;
584 }
585 Lex.Lex();
586
587 // See if the comdat was forward referenced, if so, use the comdat.
588 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
589 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
590 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
591 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
592
593 Comdat *C;
594 if (I != ComdatSymTab.end())
595 C = &I->second;
596 else
597 C = M->getOrInsertComdat(Name);
598 C->setSelectionKind(SK);
599
600 return false;
601}
602
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000603// MDString:
604// ::= '!' STRINGCONSTANT
Chris Lattner1797fc72009-12-29 21:53:55 +0000605bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000606 std::string Str;
607 if (ParseStringConstant(Str)) return true;
Chris Lattner1797fc72009-12-29 21:53:55 +0000608 Result = MDString::get(Context, Str);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000609 return false;
610}
611
612// MDNode:
613// ::= '!' MDNodeNumber
Chris Lattner6dac02a2009-12-30 04:15:23 +0000614bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000615 // !{ ..., !42, ... }
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000616 LocTy IDLoc = Lex.getLoc();
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000617 unsigned MID = 0;
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000618 if (ParseUInt32(MID))
619 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000620
Chris Lattner8eff0152010-04-01 05:14:45 +0000621 // If not a forward reference, just return it now.
David Majnemer19b51052015-02-11 07:43:56 +0000622 if (NumberedMetadata.count(MID)) {
Duncan P. N. Exon Smitha8d9a022015-01-12 21:14:38 +0000623 Result = NumberedMetadata[MID];
624 return false;
625 }
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000626
Chris Lattner8eff0152010-04-01 05:14:45 +0000627 // Otherwise, create MDNode forward reference.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000628 auto &FwdRef = ForwardRefMDNodes[MID];
Duncan P. N. Exon Smith29883862016-04-06 02:06:40 +0000629 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000630
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000631 Result = FwdRef.first.get();
632 NumberedMetadata[MID].reset(Result);
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000633 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000634}
Devang Patel8ff0f8d2009-07-20 19:00:08 +0000635
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000636/// ParseNamedMetadata:
Devang Patelbe626972009-07-29 00:34:02 +0000637/// !foo = !{ !1, !2 }
638bool LLParser::ParseNamedMetadata() {
Chris Lattnereafe4de2009-12-30 05:02:06 +0000639 assert(Lex.getKind() == lltok::MetadataVar);
Devang Patelbe626972009-07-29 00:34:02 +0000640 std::string Name = Lex.getStrVal();
Chris Lattnereafe4de2009-12-30 05:02:06 +0000641 Lex.Lex();
Devang Patelbe626972009-07-29 00:34:02 +0000642
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000643 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattner1eed2d62009-12-30 04:56:59 +0000644 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattnerf2fe7ff2009-12-29 22:35:39 +0000645 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Patelbe626972009-07-29 00:34:02 +0000646 return true;
647
Dan Gohman2637cc12010-07-21 23:38:33 +0000648 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000649 if (Lex.getKind() != lltok::rbrace)
650 do {
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000651 if (ParseToken(lltok::exclaim, "Expected '!' here"))
652 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000653
Craig Topper2617dcc2014-04-15 06:32:26 +0000654 MDNode *N = nullptr;
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000655 if (ParseMDNodeID(N)) return true;
Dan Gohman2637cc12010-07-21 23:38:33 +0000656 NMD->addOperand(N);
Dan Gohmanafd69cf2010-07-13 19:42:44 +0000657 } while (EatIfPresent(lltok::comma));
Devang Patelbe626972009-07-29 00:34:02 +0000658
Rafael Espindolac7818fb2015-05-26 20:37:36 +0000659 return ParseToken(lltok::rbrace, "expected end of metadata node");
Devang Patelbe626972009-07-29 00:34:02 +0000660}
661
Devang Patel39e64d42009-07-01 19:21:12 +0000662/// ParseStandaloneMetadata:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000663/// !42 = !{...}
Devang Patel39e64d42009-07-01 19:21:12 +0000664bool LLParser::ParseStandaloneMetadata() {
Chris Lattner1eed2d62009-12-30 04:56:59 +0000665 assert(Lex.getKind() == lltok::exclaim);
Devang Patel39e64d42009-07-01 19:21:12 +0000666 Lex.Lex();
667 unsigned MetadataID = 0;
Devang Patel39e64d42009-07-01 19:21:12 +0000668
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000669 MDNode *Init;
Chris Lattner278bc952009-12-29 22:40:21 +0000670 if (ParseUInt32(MetadataID) ||
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +0000671 ParseToken(lltok::equal, "expected '=' here"))
672 return true;
673
674 // Detect common error, from old metadata syntax.
675 if (Lex.getKind() == lltok::Type)
676 return TokError("unexpected type in metadata definition");
677
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +0000678 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +0000679 if (Lex.getKind() == lltok::MetadataVar) {
680 if (ParseSpecializedMDNode(Init, IsDistinct))
681 return true;
682 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
683 ParseMDTuple(Init, IsDistinct))
Devang Patele059ba6e2009-07-23 01:07:34 +0000684 return true;
685
Chris Lattnerfc58af22009-12-30 04:51:58 +0000686 // See if this was forward referenced, if so, handle it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000687 auto FI = ForwardRefMDNodes.find(MetadataID);
Devang Pateld2541152009-07-08 19:23:54 +0000688 if (FI != ForwardRefMDNodes.end()) {
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000689 FI->second.first->replaceAllUsesWith(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000690 ForwardRefMDNodes.erase(FI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000691
Chris Lattnerfc58af22009-12-30 04:51:58 +0000692 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
693 } else {
David Majnemer19b51052015-02-11 07:43:56 +0000694 if (NumberedMetadata.count(MetadataID))
Chris Lattnerfc58af22009-12-30 04:51:58 +0000695 return TokError("Metadata id is already used");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000696 NumberedMetadata[MetadataID].reset(Init);
Devang Pateld2541152009-07-08 19:23:54 +0000697 }
698
Devang Patel39e64d42009-07-01 19:21:12 +0000699 return false;
700}
701
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000702static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
703 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
704 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
705}
706
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000707/// parseIndirectSymbol:
Rafael Espindola464fe022014-07-30 22:51:54 +0000708/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
709/// OptionalDLLStorageClass OptionalThreadLocal
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000710/// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
Rafael Espindola6b238632014-05-16 19:35:39 +0000711///
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000712/// IndirectSymbol
Chris Lattner4c73d7a2009-04-25 21:26:00 +0000713/// ::= TypeAndValue
Chris Lattnerac161bf2009-01-02 07:01:27 +0000714///
Eric Christopher536f0a92015-05-28 23:07:39 +0000715/// Everything through OptionalUnnamedAddr has already been parsed.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000716///
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000717bool LLParser::parseIndirectSymbol(
718 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
719 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
720 GlobalVariable::UnnamedAddr UnnamedAddr) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000721 bool IsAlias;
722 if (Lex.getKind() == lltok::kw_alias)
723 IsAlias = true;
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000724 else if (Lex.getKind() == lltok::kw_ifunc)
725 IsAlias = false;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000726 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000727 llvm_unreachable("Not an alias or ifunc!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000728 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000729
Rafael Espindola78527052013-10-06 15:10:43 +0000730 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
731
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000732 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola464fe022014-07-30 22:51:54 +0000733 return Error(NameLoc, "invalid linkage type for alias");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000734
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000735 if (!isValidVisibilityForLinkage(Visibility, L))
Rafael Espindola464fe022014-07-30 22:51:54 +0000736 return Error(NameLoc,
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000737 "symbol with local linkage must have default visibility");
738
David Blaikie2f408302015-09-11 03:22:04 +0000739 Type *Ty;
740 LocTy ExplicitTypeLoc = Lex.getLoc();
741 if (ParseType(Ty) ||
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000742 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
David Blaikie2f408302015-09-11 03:22:04 +0000743 return true;
744
Rafael Espindola64c1e182014-06-03 02:41:57 +0000745 Constant *Aliasee;
746 LocTy AliaseeLoc = Lex.getLoc();
747 if (Lex.getKind() != lltok::kw_bitcast &&
748 Lex.getKind() != lltok::kw_getelementptr &&
749 Lex.getKind() != lltok::kw_addrspacecast &&
750 Lex.getKind() != lltok::kw_inttoptr) {
751 if (ParseGlobalTypeAndValue(Aliasee))
Rafael Espindola6b238632014-05-16 19:35:39 +0000752 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000753 } else {
Rafael Espindola64c1e182014-06-03 02:41:57 +0000754 // The bitcast dest type is not present, it is implied by the dest type.
755 ValID ID;
756 if (ParseValID(ID))
757 return true;
758 if (ID.Kind != ValID::t_Constant)
759 return Error(AliaseeLoc, "invalid aliasee");
760 Aliasee = ID.ConstantVal;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000761 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000762
Rafael Espindola64c1e182014-06-03 02:41:57 +0000763 Type *AliaseeType = Aliasee->getType();
764 auto *PTy = dyn_cast<PointerType>(AliaseeType);
765 if (!PTy)
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000766 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
David Blaikie16a2f3e2015-09-14 18:01:59 +0000767 unsigned AddrSpace = PTy->getAddressSpace();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000768
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000769 if (IsAlias && Ty != PTy->getElementType())
David Blaikie2f408302015-09-11 03:22:04 +0000770 return Error(
771 ExplicitTypeLoc,
772 "explicit pointee type doesn't match operand's pointee type");
773
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000774 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
775 return Error(
776 ExplicitTypeLoc,
777 "explicit pointee type should be a function type");
778
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000779 GlobalValue *GVal = nullptr;
780
781 // See if the alias was forward referenced, if so, prepare to replace the
782 // forward reference.
783 if (!Name.empty()) {
784 GVal = M->getNamedValue(Name);
785 if (GVal) {
786 if (!ForwardRefVals.erase(Name))
787 return Error(NameLoc, "redefinition of global '@" + Name + "'");
788 }
789 } else {
790 auto I = ForwardRefValIDs.find(NumberedVals.size());
791 if (I != ForwardRefValIDs.end()) {
792 GVal = I->second.first;
793 ForwardRefValIDs.erase(I);
794 }
795 }
796
Chris Lattnerac161bf2009-01-02 07:01:27 +0000797 // Okay, create the alias but do not insert it into the module yet.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000798 std::unique_ptr<GlobalIndirectSymbol> GA;
799 if (IsAlias)
800 GA.reset(GlobalAlias::create(Ty, AddrSpace,
801 (GlobalValue::LinkageTypes)Linkage, Name,
802 Aliasee, /*Parent*/ nullptr));
803 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000804 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
805 (GlobalValue::LinkageTypes)Linkage, Name,
806 Aliasee, /*Parent*/ nullptr));
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000807 GA->setThreadLocalMode(TLM);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000808 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000809 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000810 GA->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000811
Rafael Espindola54fc2982015-06-17 17:53:31 +0000812 if (Name.empty())
813 NumberedVals.push_back(GA.get());
814
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000815 if (GVal) {
816 // Verify that types agree.
817 if (GVal->getType() != GA->getType())
818 return Error(
819 ExplicitTypeLoc,
820 "forward reference and definition of alias have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000821
Chris Lattnerac161bf2009-01-02 07:01:27 +0000822 // If they agree, just RAUW the old value with the alias and remove the
823 // forward ref info.
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000824 GVal->replaceAllUsesWith(GA.get());
825 GVal->eraseFromParent();
Chris Lattnerac161bf2009-01-02 07:01:27 +0000826 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000827
Chris Lattnerac161bf2009-01-02 07:01:27 +0000828 // Insert into the module, we know its name won't collide now.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000829 if (IsAlias)
830 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
831 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000832 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
Benjamin Kramer1dc34b42010-10-16 11:28:23 +0000833 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000834
Rafael Espindolaaa273822014-05-09 21:49:17 +0000835 // The module owns this now
836 GA.release();
837
Chris Lattnerac161bf2009-01-02 07:01:27 +0000838 return false;
839}
840
841/// ParseGlobal
Nico Rieck7157bb72014-01-14 15:22:47 +0000842/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000843/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000844/// OptionalExternallyInitialized GlobalType Type Const
Nico Rieck7157bb72014-01-14 15:22:47 +0000845/// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
Eric Christopher536f0a92015-05-28 23:07:39 +0000846/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000847/// OptionalExternallyInitialized GlobalType Type Const
Chris Lattnerac161bf2009-01-02 07:01:27 +0000848///
Eric Christopher536f0a92015-05-28 23:07:39 +0000849/// Everything up to and including OptionalUnnamedAddr has been parsed
David Majnemerc4ab61c2014-03-09 06:41:58 +0000850/// already.
Chris Lattnerac161bf2009-01-02 07:01:27 +0000851///
852bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
853 unsigned Linkage, bool HasLinkage,
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000854 unsigned Visibility, unsigned DLLStorageClass,
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000855 GlobalVariable::ThreadLocalMode TLM,
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000856 GlobalVariable::UnnamedAddr UnnamedAddr) {
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +0000857 if (!isValidVisibilityForLinkage(Visibility, Linkage))
858 return Error(NameLoc,
859 "symbol with local linkage must have default visibility");
860
Chris Lattnerac161bf2009-01-02 07:01:27 +0000861 unsigned AddrSpace;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +0000862 bool IsConstant, IsExternallyInitialized;
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000863 LocTy IsExternallyInitializedLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000864 LocTy TyLoc;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000865
Craig Topper2617dcc2014-04-15 06:32:26 +0000866 Type *Ty = nullptr;
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000867 if (ParseOptionalAddrSpace(AddrSpace) ||
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000868 ParseOptionalToken(lltok::kw_externally_initialized,
869 IsExternallyInitialized,
870 &IsExternallyInitializedLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +0000871 ParseGlobalType(IsConstant) ||
872 ParseType(Ty, TyLoc))
873 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000874
Chris Lattnerac161bf2009-01-02 07:01:27 +0000875 // If the linkage is specified and is external, then no initializer is
876 // present.
Craig Topper2617dcc2014-04-15 06:32:26 +0000877 Constant *Init = nullptr;
Rafael Espindola4787ba32016-05-11 13:51:39 +0000878 if (!HasLinkage ||
879 !GlobalValue::isValidDeclarationLinkage(
880 (GlobalValue::LinkageTypes)Linkage)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +0000881 if (ParseGlobalValue(Ty, Init))
882 return true;
883 }
884
David Majnemer49b3d9b2015-02-16 08:41:08 +0000885 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
Chris Lattnerc9e1b482009-02-08 20:00:15 +0000886 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000887
David Majnemer598bd052014-12-09 05:56:09 +0000888 GlobalValue *GVal = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000889
890 // See if the global was forward referenced, if so, use the global.
Chris Lattner1f386b82009-02-02 07:24:28 +0000891 if (!Name.empty()) {
David Majnemer598bd052014-12-09 05:56:09 +0000892 GVal = M->getNamedValue(Name);
893 if (GVal) {
Peter Collingbourne463ff6d2015-11-25 02:54:07 +0000894 if (!ForwardRefVals.erase(Name))
Chris Lattnere38317f2009-10-25 23:22:50 +0000895 return Error(NameLoc, "redefinition of global '@" + Name + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +0000896 }
Chris Lattnerac161bf2009-01-02 07:01:27 +0000897 } else {
David Blaikie9ebdc692015-09-21 21:07:50 +0000898 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +0000899 if (I != ForwardRefValIDs.end()) {
David Majnemer598bd052014-12-09 05:56:09 +0000900 GVal = I->second.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000901 ForwardRefValIDs.erase(I);
902 }
903 }
904
David Majnemer598bd052014-12-09 05:56:09 +0000905 GlobalVariable *GV;
906 if (!GVal) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000907 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
908 Name, nullptr, GlobalVariable::NotThreadLocal,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000909 AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +0000910 } else {
David Blaikie8f27ae42015-05-13 22:55:01 +0000911 if (GVal->getValueType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +0000912 return Error(TyLoc,
913 "forward reference and definition of global have different types");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000914
David Majnemer598bd052014-12-09 05:56:09 +0000915 GV = cast<GlobalVariable>(GVal);
916
Chris Lattnerac161bf2009-01-02 07:01:27 +0000917 // Move the forward-reference to the correct spot in the module.
918 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
919 }
920
921 if (Name.empty())
922 NumberedVals.push_back(GV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000923
Chris Lattnerac161bf2009-01-02 07:01:27 +0000924 // Set the parsed properties on the global.
925 if (Init)
926 GV->setInitializer(Init);
927 GV->setConstant(IsConstant);
928 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
929 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +0000930 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Michael Gottesman27e7ef32013-02-05 05:57:38 +0000931 GV->setExternallyInitialized(IsExternallyInitialized);
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000932 GV->setThreadLocalMode(TLM);
Rafael Espindola45e6c192011-01-08 16:42:36 +0000933 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000934
Chris Lattnerac161bf2009-01-02 07:01:27 +0000935 // Parse attributes on the global.
936 while (Lex.getKind() == lltok::comma) {
937 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000938
Chris Lattnerac161bf2009-01-02 07:01:27 +0000939 if (Lex.getKind() == lltok::kw_section) {
940 Lex.Lex();
941 GV->setSection(Lex.getStrVal());
942 if (ParseToken(lltok::StringConstant, "expected global section string"))
943 return true;
944 } else if (Lex.getKind() == lltok::kw_align) {
945 unsigned Alignment;
946 if (ParseOptionalAlignment(Alignment)) return true;
947 GV->setAlignment(Alignment);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000948 } else if (Lex.getKind() == lltok::MetadataVar) {
949 if (ParseGlobalObjectMetadataAttachment(*GV))
950 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +0000951 } else {
David Majnemerdad0a642014-06-27 18:19:56 +0000952 Comdat *C;
Rafael Espindola83a362c2015-01-06 22:55:16 +0000953 if (parseOptionalComdat(Name, C))
David Majnemerdad0a642014-06-27 18:19:56 +0000954 return true;
955 if (C)
956 GV->setComdat(C);
957 else
958 return TokError("unknown global variable property!");
Chris Lattnerac161bf2009-01-02 07:01:27 +0000959 }
960 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000961
Chris Lattnerac161bf2009-01-02 07:01:27 +0000962 return false;
963}
964
Bill Wendling63b88192013-02-06 06:52:58 +0000965/// ParseUnnamedAttrGrp
Bill Wendlinga7c38772013-02-09 15:48:49 +0000966/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
Bill Wendling63b88192013-02-06 06:52:58 +0000967bool LLParser::ParseUnnamedAttrGrp() {
Bill Wendlinga7c38772013-02-09 15:48:49 +0000968 assert(Lex.getKind() == lltok::kw_attributes);
Bill Wendling63b88192013-02-06 06:52:58 +0000969 LocTy AttrGrpLoc = Lex.getLoc();
Bill Wendlinga7c38772013-02-09 15:48:49 +0000970 Lex.Lex();
971
David Majnemerb39e22b2014-12-09 18:33:57 +0000972 if (Lex.getKind() != lltok::AttrGrpID)
973 return TokError("expected attribute group id");
974
Bill Wendling63b88192013-02-06 06:52:58 +0000975 unsigned VarID = Lex.getUIntVal();
Bill Wendlingb32b0412013-02-08 06:32:06 +0000976 std::vector<unsigned> unused;
Michael Gottesman41748d72013-06-27 00:25:01 +0000977 LocTy BuiltinLoc;
Bill Wendling63b88192013-02-06 06:52:58 +0000978 Lex.Lex();
979
980 if (ParseToken(lltok::equal, "expected '=' here") ||
Bill Wendling63b88192013-02-06 06:52:58 +0000981 ParseToken(lltok::lbrace, "expected '{' here") ||
Bill Wendling09bd1f72013-02-22 00:12:35 +0000982 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
Michael Gottesman41748d72013-06-27 00:25:01 +0000983 BuiltinLoc) ||
Bill Wendling63b88192013-02-06 06:52:58 +0000984 ParseToken(lltok::rbrace, "expected end of attribute group"))
985 return true;
986
Bill Wendlingb32b0412013-02-08 06:32:06 +0000987 if (!NumberedAttrBuilders[VarID].hasAttributes())
Bill Wendling63b88192013-02-06 06:52:58 +0000988 return Error(AttrGrpLoc, "attribute group has no attributes");
989
990 return false;
991}
992
Bill Wendling8b0321d2013-02-08 00:52:31 +0000993/// ParseFnAttributeValuePairs
Bill Wendling63b88192013-02-06 06:52:58 +0000994/// ::= <attr> | <attr> '=' <value>
Bill Wendlingb32b0412013-02-08 06:32:06 +0000995bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
996 std::vector<unsigned> &FwdRefAttrGrps,
Michael Gottesman41748d72013-06-27 00:25:01 +0000997 bool inAttrGrp, LocTy &BuiltinLoc) {
Bill Wendling8b0321d2013-02-08 00:52:31 +0000998 bool HaveError = false;
999
1000 B.clear();
1001
Bill Wendling63b88192013-02-06 06:52:58 +00001002 while (true) {
1003 lltok::Kind Token = Lex.getKind();
Michael Gottesman41748d72013-06-27 00:25:01 +00001004 if (Token == lltok::kw_builtin)
1005 BuiltinLoc = Lex.getLoc();
Bill Wendling63b88192013-02-06 06:52:58 +00001006 switch (Token) {
1007 default:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001008 if (!inAttrGrp) return HaveError;
Bill Wendling63b88192013-02-06 06:52:58 +00001009 return Error(Lex.getLoc(), "unterminated attribute group");
1010 case lltok::rbrace:
1011 // Finished.
1012 return false;
1013
Bill Wendlingb32b0412013-02-08 06:32:06 +00001014 case lltok::AttrGrpID: {
1015 // Allow a function to reference an attribute group:
1016 //
1017 // define void @foo() #1 { ... }
1018 if (inAttrGrp)
1019 HaveError |=
1020 Error(Lex.getLoc(),
1021 "cannot have an attribute group reference in an attribute group");
1022
1023 unsigned AttrGrpNum = Lex.getUIntVal();
1024 if (inAttrGrp) break;
1025
1026 // Save the reference to the attribute group. We'll fill it in later.
1027 FwdRefAttrGrps.push_back(AttrGrpNum);
1028 break;
1029 }
Bill Wendling63b88192013-02-06 06:52:58 +00001030 // Target-dependent attributes:
1031 case lltok::StringConstant: {
Artur Pilipenko17376c42015-08-03 14:31:49 +00001032 if (ParseStringAttribute(B))
Bill Wendling63b88192013-02-06 06:52:58 +00001033 return true;
Bill Wendlingb1ea9802013-02-10 10:12:50 +00001034 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001035 }
1036
1037 // Target-independent attributes:
1038 case lltok::kw_align: {
Bill Wendlingc62789f2013-04-18 18:30:16 +00001039 // As a hack, we allow function alignment to be initially parsed as an
1040 // attribute on a function declaration/definition or added to an attribute
1041 // group and later moved to the alignment field.
Bill Wendling63b88192013-02-06 06:52:58 +00001042 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001043 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001044 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001045 if (ParseToken(lltok::equal, "expected '=' here") ||
1046 ParseUInt32(Alignment))
1047 return true;
1048 } else {
1049 if (ParseOptionalAlignment(Alignment))
1050 return true;
1051 }
Bill Wendling63b88192013-02-06 06:52:58 +00001052 B.addAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001053 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001054 }
1055 case lltok::kw_alignstack: {
1056 unsigned Alignment;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001057 if (inAttrGrp) {
Bill Wendling44b08bf2013-02-10 23:15:51 +00001058 Lex.Lex();
Bill Wendling8b0321d2013-02-08 00:52:31 +00001059 if (ParseToken(lltok::equal, "expected '=' here") ||
1060 ParseUInt32(Alignment))
1061 return true;
1062 } else {
1063 if (ParseOptionalStackAlignment(Alignment))
1064 return true;
1065 }
Bill Wendling63b88192013-02-06 06:52:58 +00001066 B.addStackAlignmentAttr(Alignment);
Bill Wendling8b0321d2013-02-08 00:52:31 +00001067 continue;
Bill Wendling63b88192013-02-06 06:52:58 +00001068 }
George Burgess IV278199f2016-04-12 01:05:35 +00001069 case lltok::kw_allocsize: {
1070 unsigned ElemSizeArg;
1071 Optional<unsigned> NumElemsArg;
1072 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1073 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1074 return true;
1075 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1076 continue;
1077 }
Igor Laevsky39d662f2015-07-11 10:30:36 +00001078 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1079 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1080 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1081 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1082 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001083 case lltok::kw_inaccessiblememonly:
1084 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1085 case lltok::kw_inaccessiblemem_or_argmemonly:
1086 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001087 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1088 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1089 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1090 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1091 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1092 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1093 case lltok::kw_noimplicitfloat:
1094 B.addAttribute(Attribute::NoImplicitFloat); break;
1095 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1096 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1097 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1098 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
James Molloye6f87ca2015-11-06 10:32:53 +00001099 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001100 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1101 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1102 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1103 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1104 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1105 case lltok::kw_returns_twice:
1106 B.addAttribute(Attribute::ReturnsTwice); break;
1107 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1108 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1109 case lltok::kw_sspstrong:
1110 B.addAttribute(Attribute::StackProtectStrong); break;
1111 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1112 case lltok::kw_sanitize_address:
1113 B.addAttribute(Attribute::SanitizeAddress); break;
1114 case lltok::kw_sanitize_thread:
1115 B.addAttribute(Attribute::SanitizeThread); break;
1116 case lltok::kw_sanitize_memory:
1117 B.addAttribute(Attribute::SanitizeMemory); break;
1118 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001119 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling8b0321d2013-02-08 00:52:31 +00001120
1121 // Error handling.
1122 case lltok::kw_inreg:
1123 case lltok::kw_signext:
1124 case lltok::kw_zeroext:
1125 HaveError |=
1126 Error(Lex.getLoc(),
1127 "invalid use of attribute on a function");
1128 break;
1129 case lltok::kw_byval:
Hal Finkelb0407ba2014-07-18 15:51:28 +00001130 case lltok::kw_dereferenceable:
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001131 case lltok::kw_dereferenceable_or_null:
Reid Klecknera534a382013-12-19 02:14:12 +00001132 case lltok::kw_inalloca:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001133 case lltok::kw_nest:
1134 case lltok::kw_noalias:
1135 case lltok::kw_nocapture:
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001136 case lltok::kw_nonnull:
Stephen Linb8bd2322013-04-20 05:14:40 +00001137 case lltok::kw_returned:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001138 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001139 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001140 case lltok::kw_swiftself:
Bill Wendling8b0321d2013-02-08 00:52:31 +00001141 HaveError |=
1142 Error(Lex.getLoc(),
1143 "invalid use of parameter-only attribute on a function");
1144 break;
Bill Wendling63b88192013-02-06 06:52:58 +00001145 }
1146
1147 Lex.Lex();
1148 }
1149}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001150
1151//===----------------------------------------------------------------------===//
1152// GlobalValue Reference/Resolution Routines.
1153//===----------------------------------------------------------------------===//
1154
Karl Schimpf77729782015-09-03 18:06:44 +00001155static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1156 const std::string &Name) {
1157 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1158 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1159 else
1160 return new GlobalVariable(*M, PTy->getElementType(), false,
1161 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1162 nullptr, GlobalVariable::NotThreadLocal,
1163 PTy->getAddressSpace());
1164}
1165
Chris Lattnerac161bf2009-01-02 07:01:27 +00001166/// GetGlobalVal - Get a value with the specified name or ID, creating a
1167/// forward reference record if needed. This can return null if the value
1168/// exists but does not have the right type.
Chris Lattner229907c2011-07-18 04:54:35 +00001169GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerac161bf2009-01-02 07:01:27 +00001170 LocTy Loc) {
Chris Lattner229907c2011-07-18 04:54:35 +00001171 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001172 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001173 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001174 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001175 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001176
Chris Lattnerac161bf2009-01-02 07:01:27 +00001177 // Look this name up in the normal function symbol table.
1178 GlobalValue *Val =
1179 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001180
Chris Lattnerac161bf2009-01-02 07:01:27 +00001181 // If this is a forward reference for the value, see if we already created a
1182 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001183 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001184 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001185 if (I != ForwardRefVals.end())
1186 Val = I->second.first;
1187 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001188
Chris Lattnerac161bf2009-01-02 07:01:27 +00001189 // If we have the value in the symbol table or fwd-ref table, return it.
1190 if (Val) {
1191 if (Val->getType() == Ty) return Val;
1192 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001193 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001194 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001195 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001196
Chris Lattnerac161bf2009-01-02 07:01:27 +00001197 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001198 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001199 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1200 return FwdVal;
1201}
1202
Chris Lattner229907c2011-07-18 04:54:35 +00001203GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1204 PointerType *PTy = dyn_cast<PointerType>(Ty);
Craig Topper2617dcc2014-04-15 06:32:26 +00001205 if (!PTy) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001206 Error(Loc, "global variable reference must have pointer type");
Craig Topper2617dcc2014-04-15 06:32:26 +00001207 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001208 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001209
Craig Topper2617dcc2014-04-15 06:32:26 +00001210 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001211
Chris Lattnerac161bf2009-01-02 07:01:27 +00001212 // If this is a forward reference for the value, see if we already created a
1213 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00001214 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00001215 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001216 if (I != ForwardRefValIDs.end())
1217 Val = I->second.first;
1218 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001219
Chris Lattnerac161bf2009-01-02 07:01:27 +00001220 // If we have the value in the symbol table or fwd-ref table, return it.
1221 if (Val) {
1222 if (Val->getType() == Ty) return Val;
Benjamin Kramerc7583112010-09-27 17:42:11 +00001223 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00001224 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00001225 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001226 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001227
Chris Lattnerac161bf2009-01-02 07:01:27 +00001228 // Otherwise, create a new forward reference for this value and remember it.
Karl Schimpf77729782015-09-03 18:06:44 +00001229 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
Chris Lattnerac161bf2009-01-02 07:01:27 +00001230 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1231 return FwdVal;
1232}
1233
Chris Lattnerac161bf2009-01-02 07:01:27 +00001234//===----------------------------------------------------------------------===//
David Majnemerdad0a642014-06-27 18:19:56 +00001235// Comdat Reference/Resolution Routines.
1236//===----------------------------------------------------------------------===//
1237
1238Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1239 // Look this name up in the comdat symbol table.
1240 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1241 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1242 if (I != ComdatSymTab.end())
1243 return &I->second;
1244
1245 // Otherwise, create a new forward reference for this value and remember it.
1246 Comdat *C = M->getOrInsertComdat(Name);
1247 ForwardRefComdats[Name] = Loc;
1248 return C;
1249}
1250
David Majnemerdad0a642014-06-27 18:19:56 +00001251//===----------------------------------------------------------------------===//
Chris Lattnerac161bf2009-01-02 07:01:27 +00001252// Helper Routines.
1253//===----------------------------------------------------------------------===//
1254
1255/// ParseToken - If the current token has the specified kind, eat it and return
1256/// success. Otherwise, emit the specified error and return failure.
1257bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1258 if (Lex.getKind() != T)
1259 return TokError(ErrMsg);
1260 Lex.Lex();
1261 return false;
1262}
1263
Chris Lattner3822f632009-01-02 08:05:26 +00001264/// ParseStringConstant
1265/// ::= StringConstant
1266bool LLParser::ParseStringConstant(std::string &Result) {
1267 if (Lex.getKind() != lltok::StringConstant)
1268 return TokError("expected string constant");
1269 Result = Lex.getStrVal();
1270 Lex.Lex();
1271 return false;
1272}
1273
1274/// ParseUInt32
1275/// ::= uint32
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001276bool LLParser::ParseUInt32(uint32_t &Val) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001277 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1278 return TokError("expected integer");
1279 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1280 if (Val64 != unsigned(Val64))
1281 return TokError("expected 32-bit integer (too large)");
1282 Val = Val64;
1283 Lex.Lex();
1284 return false;
1285}
1286
Hal Finkelb0407ba2014-07-18 15:51:28 +00001287/// ParseUInt64
1288/// ::= uint64
1289bool LLParser::ParseUInt64(uint64_t &Val) {
1290 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1291 return TokError("expected integer");
1292 Val = Lex.getAPSIntVal().getLimitedValue();
1293 Lex.Lex();
1294 return false;
1295}
1296
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001297/// ParseTLSModel
1298/// := 'localdynamic'
1299/// := 'initialexec'
1300/// := 'localexec'
1301bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1302 switch (Lex.getKind()) {
1303 default:
1304 return TokError("expected localdynamic, initialexec or localexec");
1305 case lltok::kw_localdynamic:
1306 TLM = GlobalVariable::LocalDynamicTLSModel;
1307 break;
1308 case lltok::kw_initialexec:
1309 TLM = GlobalVariable::InitialExecTLSModel;
1310 break;
1311 case lltok::kw_localexec:
1312 TLM = GlobalVariable::LocalExecTLSModel;
1313 break;
1314 }
1315
1316 Lex.Lex();
1317 return false;
1318}
1319
1320/// ParseOptionalThreadLocal
1321/// := /*empty*/
1322/// := 'thread_local'
1323/// := 'thread_local' '(' tlsmodel ')'
1324bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1325 TLM = GlobalVariable::NotThreadLocal;
1326 if (!EatIfPresent(lltok::kw_thread_local))
1327 return false;
1328
1329 TLM = GlobalVariable::GeneralDynamicTLSModel;
1330 if (Lex.getKind() == lltok::lparen) {
1331 Lex.Lex();
1332 return ParseTLSModel(TLM) ||
1333 ParseToken(lltok::rparen, "expected ')' after thread local model");
1334 }
1335 return false;
1336}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001337
1338/// ParseOptionalAddrSpace
1339/// := /*empty*/
1340/// := 'addrspace' '(' uint32 ')'
1341bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1342 AddrSpace = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001343 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001344 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001345 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3822f632009-01-02 08:05:26 +00001346 ParseUInt32(AddrSpace) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00001347 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001348}
Chris Lattnerac161bf2009-01-02 07:01:27 +00001349
Artur Pilipenko17376c42015-08-03 14:31:49 +00001350/// ParseStringAttribute
1351/// := StringConstant
1352/// := StringConstant '=' StringConstant
1353bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1354 std::string Attr = Lex.getStrVal();
1355 Lex.Lex();
1356 std::string Val;
1357 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1358 return true;
1359 B.addAttribute(Attr, Val);
1360 return false;
1361}
1362
Bill Wendling34c2eb22012-12-04 23:40:58 +00001363/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1364bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1365 bool HaveError = false;
1366
1367 B.clear();
1368
Eugene Zelenko1804a772016-08-25 00:45:04 +00001369 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001370 lltok::Kind Token = Lex.getKind();
1371 switch (Token) {
1372 default: // End of attributes.
1373 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001374 case lltok::StringConstant: {
1375 if (ParseStringAttribute(B))
1376 return true;
1377 continue;
1378 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001379 case lltok::kw_align: {
1380 unsigned Alignment;
1381 if (ParseOptionalAlignment(Alignment))
1382 return true;
Bill Wendling68d24012012-10-08 22:20:14 +00001383 B.addAlignmentAttr(Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001384 continue;
1385 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001386 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001387 case lltok::kw_dereferenceable: {
1388 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001389 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001390 return true;
1391 B.addDereferenceableAttr(Bytes);
1392 continue;
1393 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001394 case lltok::kw_dereferenceable_or_null: {
1395 uint64_t Bytes;
1396 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1397 return true;
1398 B.addDereferenceableOrNullAttr(Bytes);
1399 continue;
1400 }
Reid Klecknera534a382013-12-19 02:14:12 +00001401 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001402 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1403 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1404 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1405 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001406 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001407 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1408 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
Stephen Linb8bd2322013-04-20 05:14:40 +00001409 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001410 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1411 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001412 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
Manman Renf46262e2016-03-29 17:37:21 +00001413 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001414 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001415 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Charles Davisbe5557e2010-02-12 00:31:15 +00001416
Stephen Lin7577ed52013-04-20 13:16:13 +00001417 case lltok::kw_alignstack:
1418 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001419 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001420 case lltok::kw_builtin:
Stephen Lin7577ed52013-04-20 13:16:13 +00001421 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001422 case lltok::kw_jumptable:
Stephen Lin7577ed52013-04-20 13:16:13 +00001423 case lltok::kw_minsize:
1424 case lltok::kw_naked:
1425 case lltok::kw_nobuiltin:
1426 case lltok::kw_noduplicate:
1427 case lltok::kw_noimplicitfloat:
1428 case lltok::kw_noinline:
1429 case lltok::kw_nonlazybind:
1430 case lltok::kw_noredzone:
1431 case lltok::kw_noreturn:
1432 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001433 case lltok::kw_optnone:
Stephen Lin7577ed52013-04-20 13:16:13 +00001434 case lltok::kw_optsize:
Stephen Lin7577ed52013-04-20 13:16:13 +00001435 case lltok::kw_returns_twice:
1436 case lltok::kw_sanitize_address:
1437 case lltok::kw_sanitize_memory:
1438 case lltok::kw_sanitize_thread:
1439 case lltok::kw_ssp:
1440 case lltok::kw_sspreq:
1441 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001442 case lltok::kw_safestack:
Stephen Lin7577ed52013-04-20 13:16:13 +00001443 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001444 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1445 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001446 }
Bill Wendling0be9c402012-09-28 22:30:18 +00001447
Bill Wendling34c2eb22012-12-04 23:40:58 +00001448 Lex.Lex();
1449 }
1450}
1451
1452/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1453bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1454 bool HaveError = false;
1455
1456 B.clear();
1457
Eugene Zelenko1804a772016-08-25 00:45:04 +00001458 while (true) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001459 lltok::Kind Token = Lex.getKind();
Bill Wendling0be9c402012-09-28 22:30:18 +00001460 switch (Token) {
Bill Wendling34c2eb22012-12-04 23:40:58 +00001461 default: // End of attributes.
1462 return HaveError;
Artur Pilipenko17376c42015-08-03 14:31:49 +00001463 case lltok::StringConstant: {
1464 if (ParseStringAttribute(B))
1465 return true;
1466 continue;
1467 }
Hal Finkelb0407ba2014-07-18 15:51:28 +00001468 case lltok::kw_dereferenceable: {
1469 uint64_t Bytes;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001470 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001471 return true;
1472 B.addDereferenceableAttr(Bytes);
1473 continue;
1474 }
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001475 case lltok::kw_dereferenceable_or_null: {
1476 uint64_t Bytes;
1477 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1478 return true;
1479 B.addDereferenceableOrNullAttr(Bytes);
1480 continue;
1481 }
Artur Pilipenko84bc62f2015-09-18 12:33:31 +00001482 case lltok::kw_align: {
1483 unsigned Alignment;
1484 if (ParseOptionalAlignment(Alignment))
1485 return true;
1486 B.addAlignmentAttr(Alignment);
1487 continue;
1488 }
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001489 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1490 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001491 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001492 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1493 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
Bill Wendling0be9c402012-09-28 22:30:18 +00001494
Bill Wendling34c2eb22012-12-04 23:40:58 +00001495 // Error handling.
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001496 case lltok::kw_byval:
Reid Klecknera534a382013-12-19 02:14:12 +00001497 case lltok::kw_inalloca:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001498 case lltok::kw_nest:
1499 case lltok::kw_nocapture:
Stephen Linb8bd2322013-04-20 05:14:40 +00001500 case lltok::kw_returned:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001501 case lltok::kw_sret:
Manman Ren9bfd0d02016-04-01 21:41:15 +00001502 case lltok::kw_swifterror:
Manman Renf46262e2016-03-29 17:37:21 +00001503 case lltok::kw_swiftself:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001504 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001505 break;
James Molloy4f6fb952012-12-20 16:04:27 +00001506
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001507 case lltok::kw_alignstack:
1508 case lltok::kw_alwaysinline:
Igor Laevsky39d662f2015-07-11 10:30:36 +00001509 case lltok::kw_argmemonly:
Michael Gottesman41748d72013-06-27 00:25:01 +00001510 case lltok::kw_builtin:
Diego Novilloc6399532013-05-24 12:26:52 +00001511 case lltok::kw_cold:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001512 case lltok::kw_inlinehint:
Tom Roeder44cb65f2014-06-05 19:29:43 +00001513 case lltok::kw_jumptable:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001514 case lltok::kw_minsize:
1515 case lltok::kw_naked:
1516 case lltok::kw_nobuiltin:
1517 case lltok::kw_noduplicate:
1518 case lltok::kw_noimplicitfloat:
1519 case lltok::kw_noinline:
1520 case lltok::kw_nonlazybind:
1521 case lltok::kw_noredzone:
1522 case lltok::kw_noreturn:
1523 case lltok::kw_nounwind:
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001524 case lltok::kw_optnone:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001525 case lltok::kw_optsize:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001526 case lltok::kw_returns_twice:
1527 case lltok::kw_sanitize_address:
1528 case lltok::kw_sanitize_memory:
1529 case lltok::kw_sanitize_thread:
1530 case lltok::kw_ssp:
1531 case lltok::kw_sspreq:
1532 case lltok::kw_sspstrong:
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001533 case lltok::kw_safestack:
Chandler Carruth9f6b59a2013-04-09 19:46:46 +00001534 case lltok::kw_uwtable:
Bill Wendling34c2eb22012-12-04 23:40:58 +00001535 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
Bill Wendling0be9c402012-09-28 22:30:18 +00001536 break;
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001537
1538 case lltok::kw_readnone:
1539 case lltok::kw_readonly:
1540 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
Bill Wendling0be9c402012-09-28 22:30:18 +00001541 }
1542
Chris Lattnerac161bf2009-01-02 07:01:27 +00001543 Lex.Lex();
1544 }
1545}
1546
Rafael Espindolac6269912016-05-10 17:16:45 +00001547static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1548 HasLinkage = true;
1549 switch (Kind) {
1550 default:
1551 HasLinkage = false;
1552 return GlobalValue::ExternalLinkage;
1553 case lltok::kw_private:
1554 return GlobalValue::PrivateLinkage;
1555 case lltok::kw_internal:
1556 return GlobalValue::InternalLinkage;
1557 case lltok::kw_weak:
1558 return GlobalValue::WeakAnyLinkage;
1559 case lltok::kw_weak_odr:
1560 return GlobalValue::WeakODRLinkage;
1561 case lltok::kw_linkonce:
1562 return GlobalValue::LinkOnceAnyLinkage;
1563 case lltok::kw_linkonce_odr:
1564 return GlobalValue::LinkOnceODRLinkage;
1565 case lltok::kw_available_externally:
1566 return GlobalValue::AvailableExternallyLinkage;
1567 case lltok::kw_appending:
1568 return GlobalValue::AppendingLinkage;
1569 case lltok::kw_common:
1570 return GlobalValue::CommonLinkage;
1571 case lltok::kw_extern_weak:
1572 return GlobalValue::ExternalWeakLinkage;
1573 case lltok::kw_external:
1574 return GlobalValue::ExternalLinkage;
1575 }
1576}
1577
Chris Lattnerac161bf2009-01-02 07:01:27 +00001578/// ParseOptionalLinkage
1579/// ::= /*empty*/
Rafael Espindola6de96a12009-01-15 20:18:42 +00001580/// ::= 'private'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001581/// ::= 'internal'
1582/// ::= 'weak'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001583/// ::= 'weak_odr'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001584/// ::= 'linkonce'
Duncan Sands12da8ce2009-03-07 15:45:40 +00001585/// ::= 'linkonce_odr'
Bill Wendling03bcd6e2010-07-01 21:55:59 +00001586/// ::= 'available_externally'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001587/// ::= 'appending'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001588/// ::= 'common'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001589/// ::= 'extern_weak'
1590/// ::= 'external'
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001591bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1592 unsigned &Visibility,
1593 unsigned &DLLStorageClass) {
Rafael Espindolac6269912016-05-10 17:16:45 +00001594 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1595 if (HasLinkage)
1596 Lex.Lex();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001597 ParseOptionalVisibility(Visibility);
1598 ParseOptionalDLLStorageClass(DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001599 return false;
1600}
1601
1602/// ParseOptionalVisibility
1603/// ::= /*empty*/
1604/// ::= 'default'
1605/// ::= 'hidden'
1606/// ::= 'protected'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001607///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001608void LLParser::ParseOptionalVisibility(unsigned &Res) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001609 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001610 default:
1611 Res = GlobalValue::DefaultVisibility;
1612 return;
1613 case lltok::kw_default:
1614 Res = GlobalValue::DefaultVisibility;
1615 break;
1616 case lltok::kw_hidden:
1617 Res = GlobalValue::HiddenVisibility;
1618 break;
1619 case lltok::kw_protected:
1620 Res = GlobalValue::ProtectedVisibility;
1621 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001622 }
1623 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001624}
1625
Nico Rieck7157bb72014-01-14 15:22:47 +00001626/// ParseOptionalDLLStorageClass
1627/// ::= /*empty*/
1628/// ::= 'dllimport'
1629/// ::= 'dllexport'
1630///
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001631void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001632 switch (Lex.getKind()) {
Rafael Espindola2615c9e2016-05-12 12:37:52 +00001633 default:
1634 Res = GlobalValue::DefaultStorageClass;
1635 return;
1636 case lltok::kw_dllimport:
1637 Res = GlobalValue::DLLImportStorageClass;
1638 break;
1639 case lltok::kw_dllexport:
1640 Res = GlobalValue::DLLExportStorageClass;
1641 break;
Nico Rieck7157bb72014-01-14 15:22:47 +00001642 }
1643 Lex.Lex();
Nico Rieck7157bb72014-01-14 15:22:47 +00001644}
1645
Chris Lattnerac161bf2009-01-02 07:01:27 +00001646/// ParseOptionalCallingConv
1647/// ::= /*empty*/
1648/// ::= 'ccc'
1649/// ::= 'fastcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001650/// ::= 'intel_ocl_bicc'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001651/// ::= 'coldcc'
1652/// ::= 'x86_stdcallcc'
1653/// ::= 'x86_fastcallcc'
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001654/// ::= 'x86_thiscallcc'
Reid Kleckner9ccce992014-10-28 01:29:26 +00001655/// ::= 'x86_vectorcallcc'
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001656/// ::= 'arm_apcscc'
1657/// ::= 'arm_aapcscc'
1658/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001659/// ::= 'msp430_intrcc'
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001660/// ::= 'avr_intrcc'
1661/// ::= 'avr_signalcc'
Che-Liang Chiou29947902010-09-25 07:46:17 +00001662/// ::= 'ptx_kernel'
1663/// ::= 'ptx_device'
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001664/// ::= 'spir_func'
1665/// ::= 'spir_kernel'
Charles Davise8f297c2013-07-12 06:02:35 +00001666/// ::= 'x86_64_sysvcc'
1667/// ::= 'x86_64_win64cc'
Andrew Tricka3a11de2013-10-31 22:12:01 +00001668/// ::= 'webkit_jscc'
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001669/// ::= 'anyregcc'
Juergen Ributzkae6250132014-01-17 19:47:03 +00001670/// ::= 'preserve_mostcc'
1671/// ::= 'preserve_allcc'
Reid Kleckner35fc3632014-12-01 21:04:44 +00001672/// ::= 'ghccc'
Manman Renf8bdd882016-04-05 22:41:47 +00001673/// ::= 'swiftcc'
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001674/// ::= 'x86_intrcc'
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001675/// ::= 'hhvmcc'
1676/// ::= 'hhvm_ccc'
Manman Ren19c7bbe2015-12-04 17:40:13 +00001677/// ::= 'cxx_fast_tlscc'
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001678/// ::= 'amdgpu_vs'
1679/// ::= 'amdgpu_tcs'
1680/// ::= 'amdgpu_tes'
1681/// ::= 'amdgpu_gs'
1682/// ::= 'amdgpu_ps'
1683/// ::= 'amdgpu_cs'
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001684/// ::= 'amdgpu_kernel'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001685/// ::= 'cc' UINT
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001686///
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001687bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00001688 switch (Lex.getKind()) {
1689 default: CC = CallingConv::C; return false;
1690 case lltok::kw_ccc: CC = CallingConv::C; break;
1691 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1692 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1693 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1694 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +00001695 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
Anton Korobeynikov8f35fab2010-05-16 09:08:45 +00001696 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +00001697 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
Anton Korobeynikova8fd40b2009-06-16 18:50:49 +00001698 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1699 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1700 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov27a0ecf2009-12-07 02:27:35 +00001701 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +00001702 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1703 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
Che-Liang Chiou29947902010-09-25 07:46:17 +00001704 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1705 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Micah Villmow48c8ddc2012-10-01 17:01:31 +00001706 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1707 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001708 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
Charles Davise8f297c2013-07-12 06:02:35 +00001709 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1710 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
Andrew Tricka3a11de2013-10-31 22:12:01 +00001711 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00001712 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +00001713 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1714 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +00001715 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
Manman Renf8bdd882016-04-05 22:41:47 +00001716 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +00001717 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +00001718 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1719 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +00001720 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +00001721 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1722 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1723 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1724 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +00001725 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
Sandeep Patel68c5f472009-09-02 08:44:58 +00001726 case lltok::kw_cc: {
Sandeep Patel68c5f472009-09-02 08:44:58 +00001727 Lex.Lex();
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00001728 return ParseUInt32(CC);
Sandeep Patel68c5f472009-09-02 08:44:58 +00001729 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00001730 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001731
Chris Lattnerac161bf2009-01-02 07:01:27 +00001732 Lex.Lex();
1733 return false;
1734}
1735
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001736/// ParseMetadataAttachment
1737/// ::= !dbg !42
1738bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1739 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1740
1741 std::string Name = Lex.getStrVal();
1742 Kind = M->getMDKindID(Name);
1743 Lex.Lex();
1744
1745 return ParseMDNode(MD);
1746}
1747
Chris Lattner5c427632009-12-30 05:31:19 +00001748/// ParseInstructionMetadata
Chris Lattner596760d2009-12-29 21:25:40 +00001749/// ::= !dbg !42 (',' !dbg !57)*
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001750bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
Chris Lattner5c427632009-12-30 05:31:19 +00001751 do {
1752 if (Lex.getKind() != lltok::MetadataVar)
1753 return TokError("expected metadata after comma");
Devang Patelba4a6fd2009-09-29 00:01:14 +00001754
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001755 unsigned MDK;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00001756 MDNode *N;
Duncan P. N. Exon Smith19717ea2015-04-24 21:21:57 +00001757 if (ParseMetadataAttachment(MDK, N))
Chris Lattner1eed2d62009-12-30 04:56:59 +00001758 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001759
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001760 Inst.setMetadata(MDK, N);
Manman Ren209b17c2013-09-28 00:22:27 +00001761 if (MDK == LLVMContext::MD_tbaa)
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00001762 InstsWithTBAATag.push_back(&Inst);
Manman Ren209b17c2013-09-28 00:22:27 +00001763
Chris Lattner596760d2009-12-29 21:25:40 +00001764 // If this is the end of the list, we're done.
Chris Lattner5c427632009-12-30 05:31:19 +00001765 } while (EatIfPresent(lltok::comma));
1766 return false;
Devang Patelea8a4b92009-09-17 23:04:48 +00001767}
1768
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001769/// ParseGlobalObjectMetadataAttachment
1770/// ::= !dbg !57
1771bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1772 unsigned MDK;
1773 MDNode *N;
1774 if (ParseMetadataAttachment(MDK, N))
1775 return true;
1776
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001777 GO.addMetadata(MDK, *N);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001778 return false;
1779}
1780
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001781/// ParseOptionalFunctionMetadata
1782/// ::= (!dbg !57)*
1783bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001784 while (Lex.getKind() == lltok::MetadataVar)
1785 if (ParseGlobalObjectMetadataAttachment(F))
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001786 return true;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001787 return false;
1788}
1789
Chris Lattnerac161bf2009-01-02 07:01:27 +00001790/// ParseOptionalAlignment
1791/// ::= /* empty */
1792/// ::= 'align' 4
1793bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1794 Alignment = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001795 if (!EatIfPresent(lltok::kw_align))
1796 return false;
Chris Lattnerd11f5142009-01-05 07:46:05 +00001797 LocTy AlignLoc = Lex.getLoc();
1798 if (ParseUInt32(Alignment)) return true;
1799 if (!isPowerOf2_32(Alignment))
1800 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmand566d2c2010-07-30 21:07:05 +00001801 if (Alignment > Value::MaximumAlignment)
Dan Gohmana7e5a242010-07-28 20:12:04 +00001802 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattnerd11f5142009-01-05 07:46:05 +00001803 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001804}
1805
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001806/// ParseOptionalDerefAttrBytes
Hal Finkelb0407ba2014-07-18 15:51:28 +00001807/// ::= /* empty */
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001808/// ::= AttrKind '(' 4 ')'
1809///
1810/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1811bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1812 uint64_t &Bytes) {
1813 assert((AttrKind == lltok::kw_dereferenceable ||
1814 AttrKind == lltok::kw_dereferenceable_or_null) &&
1815 "contract!");
1816
Hal Finkelb0407ba2014-07-18 15:51:28 +00001817 Bytes = 0;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001818 if (!EatIfPresent(AttrKind))
Hal Finkelb0407ba2014-07-18 15:51:28 +00001819 return false;
1820 LocTy ParenLoc = Lex.getLoc();
1821 if (!EatIfPresent(lltok::lparen))
1822 return Error(ParenLoc, "expected '('");
1823 LocTy DerefLoc = Lex.getLoc();
1824 if (ParseUInt64(Bytes)) return true;
1825 ParenLoc = Lex.getLoc();
1826 if (!EatIfPresent(lltok::rparen))
1827 return Error(ParenLoc, "expected ')'");
1828 if (!Bytes)
1829 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1830 return false;
1831}
1832
Chris Lattnerb2f39502009-12-30 05:44:30 +00001833/// ParseOptionalCommaAlign
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001834/// ::=
Chris Lattnerb2f39502009-12-30 05:44:30 +00001835/// ::= ',' align 4
1836///
1837/// This returns with AteExtraComma set to true if it ate an excess comma at the
1838/// end.
1839bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1840 bool &AteExtraComma) {
1841 AteExtraComma = false;
1842 while (EatIfPresent(lltok::comma)) {
1843 // Metadata at the end is an early exit.
Chris Lattnereafe4de2009-12-30 05:02:06 +00001844 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerb2f39502009-12-30 05:44:30 +00001845 AteExtraComma = true;
1846 return false;
1847 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001848
Chris Lattner95b0ff42010-04-23 00:50:50 +00001849 if (Lex.getKind() != lltok::kw_align)
1850 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sands4c5c8582010-10-21 16:07:10 +00001851
Chris Lattner95b0ff42010-04-23 00:50:50 +00001852 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerb2f39502009-12-30 05:44:30 +00001853 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001854
Devang Patelea8a4b92009-09-17 23:04:48 +00001855 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001856}
1857
George Burgess IV278199f2016-04-12 01:05:35 +00001858bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1859 Optional<unsigned> &HowManyArg) {
1860 Lex.Lex();
1861
1862 auto StartParen = Lex.getLoc();
1863 if (!EatIfPresent(lltok::lparen))
1864 return Error(StartParen, "expected '('");
1865
1866 if (ParseUInt32(BaseSizeArg))
1867 return true;
1868
1869 if (EatIfPresent(lltok::comma)) {
1870 auto HowManyAt = Lex.getLoc();
1871 unsigned HowMany;
1872 if (ParseUInt32(HowMany))
1873 return true;
1874 if (HowMany == BaseSizeArg)
1875 return Error(HowManyAt,
1876 "'allocsize' indices can't refer to the same parameter");
1877 HowManyArg = HowMany;
1878 } else
1879 HowManyArg = None;
1880
1881 auto EndParen = Lex.getLoc();
1882 if (!EatIfPresent(lltok::rparen))
1883 return Error(EndParen, "expected ')'");
1884 return false;
1885}
1886
Eli Friedmanfee02c62011-07-25 23:16:38 +00001887/// ParseScopeAndOrdering
1888/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1889/// else: ::=
1890///
1891/// This sets Scope and Ordering to the parsed values.
1892bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1893 AtomicOrdering &Ordering) {
1894 if (!isAtomic)
1895 return false;
1896
1897 Scope = CrossThread;
1898 if (EatIfPresent(lltok::kw_singlethread))
1899 Scope = SingleThread;
Tim Northovere94a5182014-03-11 10:48:52 +00001900
1901 return ParseOrdering(Ordering);
1902}
1903
1904/// ParseOrdering
1905/// ::= AtomicOrdering
1906///
1907/// This sets Ordering to the parsed value.
1908bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001909 switch (Lex.getKind()) {
1910 default: return TokError("Expected ordering on atomic instruction");
JF Bastien800f87a2016-04-06 21:19:33 +00001911 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1912 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1913 // Not specified yet:
1914 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1915 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1916 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1917 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1918 case lltok::kw_seq_cst:
1919 Ordering = AtomicOrdering::SequentiallyConsistent;
1920 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001921 }
1922 Lex.Lex();
1923 return false;
1924}
1925
Charles Davisbe5557e2010-02-12 00:31:15 +00001926/// ParseOptionalStackAlignment
1927/// ::= /* empty */
1928/// ::= 'alignstack' '(' 4 ')'
1929bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1930 Alignment = 0;
1931 if (!EatIfPresent(lltok::kw_alignstack))
1932 return false;
1933 LocTy ParenLoc = Lex.getLoc();
1934 if (!EatIfPresent(lltok::lparen))
1935 return Error(ParenLoc, "expected '('");
1936 LocTy AlignLoc = Lex.getLoc();
1937 if (ParseUInt32(Alignment)) return true;
1938 ParenLoc = Lex.getLoc();
1939 if (!EatIfPresent(lltok::rparen))
1940 return Error(ParenLoc, "expected ')'");
1941 if (!isPowerOf2_32(Alignment))
1942 return Error(AlignLoc, "stack alignment is not a power of two");
1943 return false;
1944}
Devang Patelea8a4b92009-09-17 23:04:48 +00001945
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001946/// ParseIndexList - This parses the index list for an insert/extractvalue
1947/// instruction. This sets AteExtraComma in the case where we eat an extra
1948/// comma at the end of the line and find that it is followed by metadata.
1949/// Clients that don't allow metadata can call the version of this function that
1950/// only takes one argument.
1951///
Chris Lattnerac161bf2009-01-02 07:01:27 +00001952/// ParseIndexList
1953/// ::= (',' uint32)+
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001954///
1955bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1956 bool &AteExtraComma) {
1957 AteExtraComma = false;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001958
Chris Lattnerac161bf2009-01-02 07:01:27 +00001959 if (Lex.getKind() != lltok::comma)
1960 return TokError("expected ',' as start of index list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001961
Chris Lattner3822f632009-01-02 08:05:26 +00001962 while (EatIfPresent(lltok::comma)) {
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001963 if (Lex.getKind() == lltok::MetadataVar) {
David Majnemer7ccc34d2015-02-16 09:18:13 +00001964 if (Indices.empty()) return TokError("expected index");
Chris Lattner28f1eeb2009-12-30 05:14:00 +00001965 AteExtraComma = true;
1966 return false;
1967 }
Nick Lewycky83e47112010-09-29 23:32:20 +00001968 unsigned Idx = 0;
Chris Lattner3822f632009-01-02 08:05:26 +00001969 if (ParseUInt32(Idx)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001970 Indices.push_back(Idx);
1971 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001972
Chris Lattnerac161bf2009-01-02 07:01:27 +00001973 return false;
1974}
1975
1976//===----------------------------------------------------------------------===//
1977// Type Parsing.
1978//===----------------------------------------------------------------------===//
1979
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001980/// ParseType - Parse a type.
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001981bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001982 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001983 switch (Lex.getKind()) {
1984 default:
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00001985 return TokError(Msg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00001986 case lltok::Type:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001987 // Type ::= 'float' | 'void' (etc)
Chris Lattnerac161bf2009-01-02 07:01:27 +00001988 Result = Lex.getTyVal();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001989 Lex.Lex();
Chris Lattnerac161bf2009-01-02 07:01:27 +00001990 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00001991 case lltok::lbrace:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001992 // Type ::= StructType
1993 if (ParseAnonStructType(Result, false))
Chris Lattnerac161bf2009-01-02 07:01:27 +00001994 return true;
1995 break;
1996 case lltok::lsquare:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001997 // Type ::= '[' ... ']'
Chris Lattnerac161bf2009-01-02 07:01:27 +00001998 Lex.Lex(); // eat the lsquare.
1999 if (ParseArrayVectorType(Result, false))
2000 return true;
2001 break;
2002 case lltok::less: // Either vector or packed struct.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002003 // Type ::= '<' ... '>'
Chris Lattner3822f632009-01-02 08:05:26 +00002004 Lex.Lex();
2005 if (Lex.getKind() == lltok::lbrace) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002006 if (ParseAnonStructType(Result, true) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002007 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002008 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002009 } else if (ParseArrayVectorType(Result, true))
2010 return true;
2011 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002012 case lltok::LocalVar: {
2013 // Type ::= %foo
2014 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002015
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002016 // If the type hasn't been defined yet, create a forward definition and
2017 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002018 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002019 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002020 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002021 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002022 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002023 Lex.Lex();
2024 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002025 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002026
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002027 case lltok::LocalVarID: {
2028 // Type ::= %4
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002029 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002030
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002031 // If the type hasn't been defined yet, create a forward definition and
2032 // remember where that forward def'n was seen (in case it never is defined).
Craig Topper2617dcc2014-04-15 06:32:26 +00002033 if (!Entry.first) {
Chris Lattner335d3992011-08-12 18:06:37 +00002034 Entry.first = StructType::create(Context);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002035 Entry.second = Lex.getLoc();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002036 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002037 Result = Entry.first;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002038 Lex.Lex();
2039 break;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002040 }
2041 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002042
2043 // Parse the type suffixes.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002044 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002045 switch (Lex.getKind()) {
2046 // End of type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002047 default:
2048 if (!AllowVoid && Result->isVoidTy())
2049 return Error(TypeLoc, "void type only allowed for function results");
2050 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002051
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002052 // Type ::= Type '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002053 case lltok::star:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002054 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002055 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002056 if (Result->isVoidTy())
2057 return TokError("pointers to void are invalid - use i8* instead");
2058 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002059 return TokError("pointer to this type is invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002060 Result = PointerType::getUnqual(Result);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002061 Lex.Lex();
2062 break;
2063
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002064 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002065 case lltok::kw_addrspace: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002066 if (Result->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002067 return TokError("basic block pointers are invalid");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002068 if (Result->isVoidTy())
Dan Gohman9280a682009-02-09 17:41:21 +00002069 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002070 if (!PointerType::isValidElementType(Result))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002071 return TokError("pointer to this type is invalid");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002072 unsigned AddrSpace;
2073 if (ParseOptionalAddrSpace(AddrSpace) ||
2074 ParseToken(lltok::star, "expected '*' in address space"))
2075 return true;
2076
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002077 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002078 break;
2079 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002080
Chris Lattnerac161bf2009-01-02 07:01:27 +00002081 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2082 case lltok::lparen:
2083 if (ParseFunctionType(Result))
2084 return true;
2085 break;
2086 }
2087 }
2088}
2089
2090/// ParseParameterList
2091/// ::= '(' ')'
2092/// ::= '(' Arg (',' Arg)* ')'
2093/// Arg
2094/// ::= Type OptionalAttributes Value OptionalAttributes
2095bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
Reid Kleckner83498642014-08-26 00:33:28 +00002096 PerFunctionState &PFS, bool IsMustTailCall,
2097 bool InVarArgsFunc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002098 if (ParseToken(lltok::lparen, "expected '(' in call"))
2099 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002100
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002101 unsigned AttrIndex = 1;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002102 while (Lex.getKind() != lltok::rparen) {
2103 // If this isn't the first argument, we need a comma.
2104 if (!ArgList.empty() &&
2105 ParseToken(lltok::comma, "expected ',' in argument list"))
2106 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002107
Reid Kleckner83498642014-08-26 00:33:28 +00002108 // Parse an ellipsis if this is a musttail call in a variadic function.
2109 if (Lex.getKind() == lltok::dotdotdot) {
2110 const char *Msg = "unexpected ellipsis in argument list for ";
2111 if (!IsMustTailCall)
2112 return TokError(Twine(Msg) + "non-musttail call");
2113 if (!InVarArgsFunc)
2114 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2115 Lex.Lex(); // Lex the '...', it is purely for readability.
2116 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2117 }
2118
Chris Lattnerac161bf2009-01-02 07:01:27 +00002119 // Parse the argument.
2120 LocTy ArgLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00002121 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002122 AttrBuilder ArgAttrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002123 Value *V;
Victor Hernandezfa232232009-12-03 23:40:58 +00002124 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002125 return true;
Victor Hernandezfa232232009-12-03 23:40:58 +00002126
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00002127 if (ArgTy->isMetadataTy()) {
2128 if (ParseMetadataAsValue(V, PFS))
2129 return true;
2130 } else {
2131 // Otherwise, handle normal operands.
2132 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2133 return true;
2134 }
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002135 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2136 AttrIndex++,
2137 ArgAttrs)));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002138 }
2139
Reid Kleckner83498642014-08-26 00:33:28 +00002140 if (IsMustTailCall && InVarArgsFunc)
2141 return TokError("expected '...' at end of argument list for musttail call "
2142 "in varargs function");
2143
Chris Lattnerac161bf2009-01-02 07:01:27 +00002144 Lex.Lex(); // Lex the ')'.
2145 return false;
2146}
2147
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002148/// ParseOptionalOperandBundles
2149/// ::= /*empty*/
2150/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2151///
2152/// OperandBundle
2153/// ::= bundle-tag '(' ')'
2154/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2155///
2156/// bundle-tag ::= String Constant
2157bool LLParser::ParseOptionalOperandBundles(
2158 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2159 LocTy BeginLoc = Lex.getLoc();
2160 if (!EatIfPresent(lltok::lsquare))
2161 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002162
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002163 while (Lex.getKind() != lltok::rsquare) {
2164 // If this isn't the first operand bundle, we need a comma.
2165 if (!BundleList.empty() &&
2166 ParseToken(lltok::comma, "expected ',' in input list"))
2167 return true;
2168
2169 std::string Tag;
2170 if (ParseStringConstant(Tag))
2171 return true;
2172
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002173 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2174 return true;
2175
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002176 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002177 while (Lex.getKind() != lltok::rparen) {
2178 // If this isn't the first input, we need a comma.
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002179 if (!Inputs.empty() &&
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002180 ParseToken(lltok::comma, "expected ',' in input list"))
2181 return true;
2182
2183 Type *Ty = nullptr;
2184 Value *Input = nullptr;
2185 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2186 return true;
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002187 Inputs.push_back(Input);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002188 }
2189
Sanjoy Dasf79d3442015-11-18 08:30:07 +00002190 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2191
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002192 Lex.Lex(); // Lex the ')'.
2193 }
2194
2195 if (BundleList.empty())
2196 return Error(BeginLoc, "operand bundle set must not be empty");
2197
2198 Lex.Lex(); // Lex the ']'.
2199 return false;
2200}
Chris Lattnerac161bf2009-01-02 07:01:27 +00002201
Chris Lattner2ed06b42009-01-05 18:34:07 +00002202/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002203/// prototype.
Chris Lattnerac161bf2009-01-02 07:01:27 +00002204/// ::= '(' ArgTypeListI ')'
2205/// ArgTypeListI
2206/// ::= /*empty*/
2207/// ::= '...'
2208/// ::= ArgTypeList ',' '...'
2209/// ::= ArgType (',' ArgType)*
Chris Lattner2ed06b42009-01-05 18:34:07 +00002210///
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002211bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2212 bool &isVarArg){
Chris Lattnerac161bf2009-01-02 07:01:27 +00002213 isVarArg = false;
2214 assert(Lex.getKind() == lltok::lparen);
2215 Lex.Lex(); // eat the (.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002216
Chris Lattnerac161bf2009-01-02 07:01:27 +00002217 if (Lex.getKind() == lltok::rparen) {
2218 // empty
2219 } else if (Lex.getKind() == lltok::dotdotdot) {
2220 isVarArg = true;
2221 Lex.Lex();
2222 } else {
2223 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002224 Type *ArgTy = nullptr;
Bill Wendling50d27842012-10-15 20:35:56 +00002225 AttrBuilder Attrs;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002226 std::string Name;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002227
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002228 if (ParseType(ArgTy) ||
Bill Wendling34c2eb22012-12-04 23:40:58 +00002229 ParseOptionalParamAttrs(Attrs)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002230
Chris Lattnerfdd87902009-10-05 05:54:46 +00002231 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002232 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002233
Chris Lattnerdef19492011-06-17 06:36:20 +00002234 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002235 Name = Lex.getStrVal();
2236 Lex.Lex();
2237 }
Chris Lattner3822f632009-01-02 08:05:26 +00002238
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002239 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3822f632009-01-02 08:05:26 +00002240 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002241
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002242 unsigned AttrIndex = 1;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002243 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2244 AttrIndex++, Attrs),
2245 std::move(Name));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002246
Chris Lattner3822f632009-01-02 08:05:26 +00002247 while (EatIfPresent(lltok::comma)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002248 // Handle ... at end of arg list.
Chris Lattner3822f632009-01-02 08:05:26 +00002249 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002250 isVarArg = true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002251 break;
2252 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002253
Chris Lattnerac161bf2009-01-02 07:01:27 +00002254 // Otherwise must be an argument type.
2255 TypeLoc = Lex.getLoc();
Bill Wendling34c2eb22012-12-04 23:40:58 +00002256 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
Chris Lattner3822f632009-01-02 08:05:26 +00002257
Chris Lattnerfdd87902009-10-05 05:54:46 +00002258 if (ArgTy->isVoidTy())
Chris Lattnerf880ca22009-03-09 04:49:14 +00002259 return Error(TypeLoc, "argument can not have void type");
2260
Chris Lattnerdef19492011-06-17 06:36:20 +00002261 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002262 Name = Lex.getStrVal();
2263 Lex.Lex();
2264 } else {
2265 Name = "";
2266 }
Chris Lattner3822f632009-01-02 08:05:26 +00002267
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002268 if (!ArgTy->isFirstClassType())
Chris Lattner3822f632009-01-02 08:05:26 +00002269 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002270
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002271 ArgList.emplace_back(
2272 TypeLoc, ArgTy,
2273 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2274 std::move(Name));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002275 }
2276 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002277
Chris Lattner3822f632009-01-02 08:05:26 +00002278 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002279}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002280
Chris Lattnerac161bf2009-01-02 07:01:27 +00002281/// ParseFunctionType
2282/// ::= Type ArgumentList OptionalAttrs
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002283bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002284 assert(Lex.getKind() == lltok::lparen);
2285
Chris Lattnerce473c72009-01-05 08:04:33 +00002286 if (!FunctionType::isValidReturnType(Result))
2287 return TokError("invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002288
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002289 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002290 bool isVarArg;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002291 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002292 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002293
Chris Lattnerac161bf2009-01-02 07:01:27 +00002294 // Reject names on the arguments lists.
2295 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2296 if (!ArgList[i].Name.empty())
2297 return Error(ArgList[i].Loc, "argument name invalid in function type");
Bill Wendlingfe0021a2013-01-31 00:29:54 +00002298 if (ArgList[i].Attrs.hasAttributes(i + 1))
Chris Lattner6bc5c892011-06-17 17:37:13 +00002299 return Error(ArgList[i].Loc,
2300 "argument attributes invalid in function type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002301 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002302
Jay Foadb804a2b2011-07-12 14:06:48 +00002303 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002304 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002305 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002306
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002307 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002308 return false;
2309}
2310
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002311/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2312/// other structs.
2313bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2314 SmallVector<Type*, 8> Elts;
2315 if (ParseStructBody(Elts)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002316
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002317 Result = StructType::get(Context, Elts, Packed);
2318 return false;
2319}
2320
2321/// ParseStructDefinition - Parse a struct in a 'type' definition.
2322bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2323 std::pair<Type*, LocTy> &Entry,
2324 Type *&ResultTy) {
2325 // If the type was already defined, diagnose the redefinition.
2326 if (Entry.first && !Entry.second.isValid())
2327 return Error(TypeLoc, "redefinition of type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002328
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002329 // If we have opaque, just return without filling in the definition for the
2330 // struct. This counts as a definition as far as the .ll file goes.
2331 if (EatIfPresent(lltok::kw_opaque)) {
2332 // This type is being defined, so clear the location to indicate this.
2333 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002334
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002335 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002336 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002337 Entry.first = StructType::create(Context, Name);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002338 ResultTy = Entry.first;
2339 return false;
2340 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002341
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002342 // If the type starts with '<', then it is either a packed struct or a vector.
2343 bool isPacked = EatIfPresent(lltok::less);
2344
2345 // If we don't have a struct, then we have a random type alias, which we
2346 // accept for compatibility with old files. These types are not allowed to be
2347 // forward referenced and not allowed to be recursive.
2348 if (Lex.getKind() != lltok::lbrace) {
2349 if (Entry.first)
2350 return Error(TypeLoc, "forward references to non-struct type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002351
Craig Topper2617dcc2014-04-15 06:32:26 +00002352 ResultTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002353 if (isPacked)
2354 return ParseArrayVectorType(ResultTy, true);
2355 return ParseType(ResultTy);
2356 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002357
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002358 // This type is being defined, so clear the location to indicate this.
2359 Entry.second = SMLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002360
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002361 // If this type number has never been uttered, create it.
Craig Topper2617dcc2014-04-15 06:32:26 +00002362 if (!Entry.first)
Chris Lattner335d3992011-08-12 18:06:37 +00002363 Entry.first = StructType::create(Context, Name);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002364
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002365 StructType *STy = cast<StructType>(Entry.first);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002366
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002367 SmallVector<Type*, 8> Body;
2368 if (ParseStructBody(Body) ||
2369 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2370 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002371
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002372 STy->setBody(Body, isPacked);
2373 ResultTy = STy;
2374 return false;
2375}
2376
Chris Lattnerac161bf2009-01-02 07:01:27 +00002377/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002378/// StructType
Chris Lattnerac161bf2009-01-02 07:01:27 +00002379/// ::= '{' '}'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002380/// ::= '{' Type (',' Type)* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00002381/// ::= '<' '{' '}' '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002382/// ::= '<' '{' Type (',' Type)* '}' '>'
2383bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002384 assert(Lex.getKind() == lltok::lbrace);
2385 Lex.Lex(); // Consume the '{'
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002386
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002387 // Handle the empty struct.
2388 if (EatIfPresent(lltok::rbrace))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002389 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002390
Chris Lattnerf880ca22009-03-09 04:49:14 +00002391 LocTy EltTyLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002392 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002393 if (ParseType(Ty)) return true;
2394 Body.push_back(Ty);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002395
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002396 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002397 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002398
Chris Lattner3822f632009-01-02 08:05:26 +00002399 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf880ca22009-03-09 04:49:14 +00002400 EltTyLoc = Lex.getLoc();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002401 if (ParseType(Ty)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002402
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002403 if (!StructType::isValidElementType(Ty))
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002404 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002405
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002406 Body.push_back(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002407 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002408
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002409 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002410}
2411
2412/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2413/// token has already been consumed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002414/// Type
Chris Lattnerac161bf2009-01-02 07:01:27 +00002415/// ::= '[' APSINTVAL 'x' Types ']'
2416/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002417bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002418 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2419 Lex.getAPSIntVal().getBitWidth() > 64)
2420 return TokError("expected number in address space");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002421
Chris Lattnerac161bf2009-01-02 07:01:27 +00002422 LocTy SizeLoc = Lex.getLoc();
2423 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3822f632009-01-02 08:05:26 +00002424 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002425
Chris Lattner3822f632009-01-02 08:05:26 +00002426 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2427 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002428
2429 LocTy TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00002430 Type *EltTy = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002431 if (ParseType(EltTy)) return true;
Chris Lattnerf880ca22009-03-09 04:49:14 +00002432
Chris Lattner3822f632009-01-02 08:05:26 +00002433 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2434 "expected end of sequential type"))
2435 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002436
Chris Lattnerac161bf2009-01-02 07:01:27 +00002437 if (isVector) {
Chris Lattnerbb1fe8a2009-02-28 18:12:41 +00002438 if (Size == 0)
2439 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002440 if ((unsigned)Size != Size)
2441 return Error(SizeLoc, "size too large for vector");
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002442 if (!VectorType::isValidElementType(EltTy))
Duncan Sandse6beec62012-11-13 12:59:33 +00002443 return Error(TypeLoc, "invalid vector element type");
Owen Anderson4056ca92009-07-29 22:17:13 +00002444 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002445 } else {
Nick Lewycky0aa6a742009-06-07 07:26:46 +00002446 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002447 return Error(TypeLoc, "invalid array element type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002448 Result = ArrayType::get(EltTy, Size);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002449 }
2450 return false;
2451}
2452
2453//===----------------------------------------------------------------------===//
2454// Function Semantic Analysis.
2455//===----------------------------------------------------------------------===//
2456
Chris Lattner3432c622009-10-28 03:39:23 +00002457LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2458 int functionNumber)
2459 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002460
2461 // Insert unnamed arguments into the NumberedVals list.
Duncan P. N. Exon Smithac331fb2015-10-20 01:12:49 +00002462 for (Argument &A : F.args())
2463 if (!A.hasName())
2464 NumberedVals.push_back(&A);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002465}
2466
2467LLParser::PerFunctionState::~PerFunctionState() {
2468 // If there were any forward referenced non-basicblock values, delete them.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002469
David Blaikie9ebdc692015-09-21 21:07:50 +00002470 for (const auto &P : ForwardRefVals) {
2471 if (isa<BasicBlock>(P.second.first))
2472 continue;
2473 P.second.first->replaceAllUsesWith(
2474 UndefValue::get(P.second.first->getType()));
2475 delete P.second.first;
2476 }
2477
2478 for (const auto &P : ForwardRefValIDs) {
2479 if (isa<BasicBlock>(P.second.first))
2480 continue;
2481 P.second.first->replaceAllUsesWith(
2482 UndefValue::get(P.second.first->getType()));
2483 delete P.second.first;
2484 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00002485}
2486
Chris Lattner3432c622009-10-28 03:39:23 +00002487bool LLParser::PerFunctionState::FinishFunction() {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002488 if (!ForwardRefVals.empty())
2489 return P.Error(ForwardRefVals.begin()->second.second,
2490 "use of undefined value '%" + ForwardRefVals.begin()->first +
2491 "'");
2492 if (!ForwardRefValIDs.empty())
2493 return P.Error(ForwardRefValIDs.begin()->second.second,
2494 "use of undefined value '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002495 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002496 return false;
2497}
2498
Chris Lattnerac161bf2009-01-02 07:01:27 +00002499/// GetVal - Get a value with the specified name or ID, creating a
2500/// forward reference record if needed. This can return null if the value
2501/// exists but does not have the right type.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002502Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
David Majnemer8a1c45d2015-12-12 05:38:55 +00002503 LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002504 // Look this name up in the normal function symbol table.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002505 Value *Val = F.getValueSymbolTable()->lookup(Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002506
Chris Lattnerac161bf2009-01-02 07:01:27 +00002507 // If this is a forward reference for the value, see if we already created a
2508 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002509 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002510 auto I = ForwardRefVals.find(Name);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002511 if (I != ForwardRefVals.end())
2512 Val = I->second.first;
2513 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002514
Chris Lattnerac161bf2009-01-02 07:01:27 +00002515 // If we have the value in the symbol table or fwd-ref table, return it.
2516 if (Val) {
2517 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002518 if (Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002519 P.Error(Loc, "'%" + Name + "' is not a basic block");
2520 else
2521 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002522 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002523 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002524 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002525
Chris Lattnerac161bf2009-01-02 07:01:27 +00002526 // Don't make placeholders with invalid type.
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002527 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002528 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002529 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002530 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002531
Chris Lattnerac161bf2009-01-02 07:01:27 +00002532 // Otherwise, create a new forward reference for this value and remember it.
2533 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002534 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002535 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002536 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002537 FwdVal = new Argument(Ty, Name);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002538 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002539
Chris Lattnerac161bf2009-01-02 07:01:27 +00002540 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2541 return FwdVal;
2542}
2543
David Majnemer8a1c45d2015-12-12 05:38:55 +00002544Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002545 // Look this name up in the normal function symbol table.
Craig Topper2617dcc2014-04-15 06:32:26 +00002546 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002547
Chris Lattnerac161bf2009-01-02 07:01:27 +00002548 // If this is a forward reference for the value, see if we already created a
2549 // forward ref record.
Craig Topper2617dcc2014-04-15 06:32:26 +00002550 if (!Val) {
David Blaikie9ebdc692015-09-21 21:07:50 +00002551 auto I = ForwardRefValIDs.find(ID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002552 if (I != ForwardRefValIDs.end())
2553 Val = I->second.first;
2554 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002555
Chris Lattnerac161bf2009-01-02 07:01:27 +00002556 // If we have the value in the symbol table or fwd-ref table, return it.
2557 if (Val) {
2558 if (Val->getType() == Ty) return Val;
Chris Lattnerfdd87902009-10-05 05:54:46 +00002559 if (Ty->isLabelTy())
Benjamin Kramerc7583112010-09-27 17:42:11 +00002560 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerac161bf2009-01-02 07:01:27 +00002561 else
Benjamin Kramerc7583112010-09-27 17:42:11 +00002562 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002563 getTypeString(Val->getType()) + "'");
Craig Topper2617dcc2014-04-15 06:32:26 +00002564 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002565 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002566
Duncan P. N. Exon Smith6a6e9cb2014-08-05 18:22:58 +00002567 if (!Ty->isFirstClassType()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002568 P.Error(Loc, "invalid use of a non-first-class type");
Craig Topper2617dcc2014-04-15 06:32:26 +00002569 return nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002570 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002571
Chris Lattnerac161bf2009-01-02 07:01:27 +00002572 // Otherwise, create a new forward reference for this value and remember it.
2573 Value *FwdVal;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002574 if (Ty->isLabelTy()) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002575 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002576 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002577 FwdVal = new Argument(Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002578 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002579
Chris Lattnerac161bf2009-01-02 07:01:27 +00002580 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2581 return FwdVal;
2582}
2583
2584/// SetInstName - After an instruction is parsed and inserted into its
2585/// basic block, this installs its name.
2586bool LLParser::PerFunctionState::SetInstName(int NameID,
2587 const std::string &NameStr,
2588 LocTy NameLoc, Instruction *Inst) {
2589 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnerfdd87902009-10-05 05:54:46 +00002590 if (Inst->getType()->isVoidTy()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002591 if (NameID != -1 || !NameStr.empty())
2592 return P.Error(NameLoc, "instructions returning void cannot have a name");
2593 return false;
2594 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002595
Chris Lattnerac161bf2009-01-02 07:01:27 +00002596 // If this was a numbered instruction, verify that the instruction is the
2597 // expected value and resolve any forward references.
2598 if (NameStr.empty()) {
2599 // If neither a name nor an ID was specified, just use the next ID.
2600 if (NameID == -1)
2601 NameID = NumberedVals.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002602
Chris Lattnerac161bf2009-01-02 07:01:27 +00002603 if (unsigned(NameID) != NumberedVals.size())
2604 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00002605 Twine(NumberedVals.size()) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002606
David Blaikie9ebdc692015-09-21 21:07:50 +00002607 auto FI = ForwardRefValIDs.find(NameID);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002608 if (FI != ForwardRefValIDs.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002609 Value *Sentinel = FI->second.first;
2610 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002611 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002612 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002613
2614 Sentinel->replaceAllUsesWith(Inst);
2615 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002616 ForwardRefValIDs.erase(FI);
2617 }
2618
2619 NumberedVals.push_back(Inst);
2620 return false;
2621 }
2622
2623 // Otherwise, the instruction had a name. Resolve forward refs and set it.
David Blaikie9ebdc692015-09-21 21:07:50 +00002624 auto FI = ForwardRefVals.find(NameStr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002625 if (FI != ForwardRefVals.end()) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002626 Value *Sentinel = FI->second.first;
2627 if (Sentinel->getType() != Inst->getType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002628 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002629 getTypeString(FI->second.first->getType()) + "'");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002630
2631 Sentinel->replaceAllUsesWith(Inst);
2632 delete Sentinel;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002633 ForwardRefVals.erase(FI);
2634 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002635
Chris Lattnerac161bf2009-01-02 07:01:27 +00002636 // Set the name on the instruction.
2637 Inst->setName(NameStr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002638
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00002639 if (Inst->getName() != NameStr)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002640 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerac161bf2009-01-02 07:01:27 +00002641 NameStr + "'");
2642 return false;
2643}
2644
2645/// GetBB - Get a basic block with the specified name or ID, creating a
2646/// forward reference record if needed.
2647BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2648 LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002649 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2650 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002651}
2652
2653BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson576a9a22015-03-02 05:25:09 +00002654 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2655 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002656}
2657
2658/// DefineBB - Define the specified basic block, which is either named or
2659/// unnamed. If there is an error, this returns null otherwise it returns
2660/// the block being defined.
2661BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2662 LocTy Loc) {
2663 BasicBlock *BB;
2664 if (Name.empty())
2665 BB = GetBB(NumberedVals.size(), Loc);
2666 else
2667 BB = GetBB(Name, Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002668 if (!BB) return nullptr; // Already diagnosed error.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002669
Chris Lattnerac161bf2009-01-02 07:01:27 +00002670 // Move the block to the end of the function. Forward ref'd blocks are
2671 // inserted wherever they happen to be referenced.
2672 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002673
Chris Lattnerac161bf2009-01-02 07:01:27 +00002674 // Remove the block from forward ref sets.
2675 if (Name.empty()) {
2676 ForwardRefValIDs.erase(NumberedVals.size());
2677 NumberedVals.push_back(BB);
2678 } else {
2679 // BB forward references are already in the function symbol table.
2680 ForwardRefVals.erase(Name);
2681 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002682
Chris Lattnerac161bf2009-01-02 07:01:27 +00002683 return BB;
2684}
2685
2686//===----------------------------------------------------------------------===//
2687// Constants.
2688//===----------------------------------------------------------------------===//
2689
2690/// ParseValID - Parse an abstract value that doesn't necessarily have a
2691/// type implied. For example, if we parse "4" we don't know what integer type
2692/// it has. The value will later be combined with its type and checked for
Victor Hernandezb8fd1522010-01-10 07:14:18 +00002693/// sanity. PFS is used to convert function-local operands of metadata (since
2694/// metadata operands are not just parsed here but also converted to values).
2695/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezdc6e65a2010-01-05 22:22:14 +00002696bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002697 ID.Loc = Lex.getLoc();
2698 switch (Lex.getKind()) {
2699 default: return TokError("expected value token");
2700 case lltok::GlobalID: // @42
2701 ID.UIntVal = Lex.getUIntVal();
2702 ID.Kind = ValID::t_GlobalID;
2703 break;
2704 case lltok::GlobalVar: // @foo
2705 ID.StrVal = Lex.getStrVal();
2706 ID.Kind = ValID::t_GlobalName;
2707 break;
2708 case lltok::LocalVarID: // %42
2709 ID.UIntVal = Lex.getUIntVal();
2710 ID.Kind = ValID::t_LocalID;
2711 break;
2712 case lltok::LocalVar: // %foo
Chris Lattnerac161bf2009-01-02 07:01:27 +00002713 ID.StrVal = Lex.getStrVal();
2714 ID.Kind = ValID::t_LocalName;
2715 break;
2716 case lltok::APSInt:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002717 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00002718 ID.Kind = ValID::t_APSInt;
2719 break;
2720 case lltok::APFloat:
2721 ID.APFloatVal = Lex.getAPFloatVal();
2722 ID.Kind = ValID::t_APFloat;
2723 break;
2724 case lltok::kw_true:
Owen Anderson23a204d2009-07-31 17:39:07 +00002725 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002726 ID.Kind = ValID::t_Constant;
2727 break;
2728 case lltok::kw_false:
Owen Anderson23a204d2009-07-31 17:39:07 +00002729 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002730 ID.Kind = ValID::t_Constant;
2731 break;
2732 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2733 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2734 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
David Majnemerf0f224d2015-11-11 21:57:16 +00002735 case lltok::kw_none: ID.Kind = ValID::t_None; break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002736
Chris Lattnerac161bf2009-01-02 07:01:27 +00002737 case lltok::lbrace: {
2738 // ValID ::= '{' ConstVector '}'
2739 Lex.Lex();
2740 SmallVector<Constant*, 16> Elts;
2741 if (ParseGlobalValueVector(Elts) ||
2742 ParseToken(lltok::rbrace, "expected end of struct constant"))
2743 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002744
David Blaikieadbda4b2015-08-03 20:08:41 +00002745 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002746 ID.UIntVal = Elts.size();
David Blaikieadbda4b2015-08-03 20:08:41 +00002747 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2748 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002749 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002750 return false;
2751 }
2752 case lltok::less: {
2753 // ValID ::= '<' ConstVector '>' --> Vector.
2754 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2755 Lex.Lex();
Chris Lattner3822f632009-01-02 08:05:26 +00002756 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002757
Chris Lattnerac161bf2009-01-02 07:01:27 +00002758 SmallVector<Constant*, 16> Elts;
2759 LocTy FirstEltLoc = Lex.getLoc();
2760 if (ParseGlobalValueVector(Elts) ||
2761 (isPackedStruct &&
2762 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2763 ParseToken(lltok::greater, "expected end of constant"))
2764 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002765
Chris Lattnerac161bf2009-01-02 07:01:27 +00002766 if (isPackedStruct) {
David Blaikieadbda4b2015-08-03 20:08:41 +00002767 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2768 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2769 Elts.size() * sizeof(Elts[0]));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002770 ID.UIntVal = Elts.size();
2771 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002772 return false;
2773 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002774
Chris Lattnerac161bf2009-01-02 07:01:27 +00002775 if (Elts.empty())
2776 return Error(ID.Loc, "constant vector must not be empty");
2777
Duncan Sands9dff9be2010-02-15 16:12:20 +00002778 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00002779 !Elts[0]->getType()->isFloatingPointTy() &&
2780 !Elts[0]->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00002781 return Error(FirstEltLoc,
Nadav Rotem3924cb02011-12-05 06:29:09 +00002782 "vector elements must have integer, pointer or floating point type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002783
Chris Lattnerac161bf2009-01-02 07:01:27 +00002784 // Verify that all the vector elements have the same type.
2785 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2786 if (Elts[i]->getType() != Elts[0]->getType())
2787 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002788 "vector element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002789 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002790
Chris Lattner69229312011-02-15 00:14:00 +00002791 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002792 ID.Kind = ValID::t_Constant;
2793 return false;
2794 }
2795 case lltok::lsquare: { // Array Constant
2796 Lex.Lex();
2797 SmallVector<Constant*, 16> Elts;
2798 LocTy FirstEltLoc = Lex.getLoc();
2799 if (ParseGlobalValueVector(Elts) ||
2800 ParseToken(lltok::rsquare, "expected end of array constant"))
2801 return true;
2802
2803 // Handle empty element.
2804 if (Elts.empty()) {
2805 // Use undef instead of an array because it's inconvenient to determine
2806 // the element type at this point, there being no elements to examine.
Chris Lattner998fa0a2009-01-05 07:52:51 +00002807 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002808 return false;
2809 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002810
Chris Lattnerac161bf2009-01-02 07:01:27 +00002811 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002812 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002813 getTypeString(Elts[0]->getType()));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002814
Owen Anderson4056ca92009-07-29 22:17:13 +00002815 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002816
Chris Lattnerac161bf2009-01-02 07:01:27 +00002817 // Verify all elements are correct type!
Chris Lattner59d0e3b2009-01-02 08:49:06 +00002818 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002819 if (Elts[i]->getType() != Elts[0]->getType())
2820 return Error(FirstEltLoc,
Benjamin Kramerc7583112010-09-27 17:42:11 +00002821 "array element #" + Twine(i) +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002822 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerac161bf2009-01-02 07:01:27 +00002823 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002824
Jay Foad83be3612011-06-22 09:24:39 +00002825 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002826 ID.Kind = ValID::t_Constant;
2827 return false;
2828 }
2829 case lltok::kw_c: // c "foo"
2830 Lex.Lex();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002831 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2832 false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002833 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2834 ID.Kind = ValID::t_Constant;
2835 return false;
2836
2837 case lltok::kw_asm: {
Chad Rosier6f9c3852013-02-14 20:44:07 +00002838 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2839 // STRINGCONSTANT
Chad Rosierd8c76102012-09-05 19:00:49 +00002840 bool HasSideEffect, AlignStack, AsmDialect;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002841 Lex.Lex();
2842 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002843 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chad Rosierd8c76102012-09-05 19:00:49 +00002844 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
Chris Lattner3822f632009-01-02 08:05:26 +00002845 ParseStringConstant(ID.StrVal) ||
2846 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002847 ParseToken(lltok::StringConstant, "expected constraint string"))
2848 return true;
2849 ID.StrVal2 = Lex.getStrVal();
Chad Rosierf42fad62012-09-05 00:08:17 +00002850 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
Chad Rosierd8c76102012-09-05 19:00:49 +00002851 (unsigned(AsmDialect)<<2);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002852 ID.Kind = ValID::t_InlineAsm;
2853 return false;
2854 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002855
Chris Lattner3432c622009-10-28 03:39:23 +00002856 case lltok::kw_blockaddress: {
2857 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2858 Lex.Lex();
2859
2860 ValID Fn, Label;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002861
Chris Lattner3432c622009-10-28 03:39:23 +00002862 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2863 ParseValID(Fn) ||
2864 ParseToken(lltok::comma, "expected comma in block address expression")||
2865 ParseValID(Label) ||
2866 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2867 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002868
Chris Lattner3432c622009-10-28 03:39:23 +00002869 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2870 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattneraa99c942009-11-01 01:27:45 +00002871 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner3432c622009-10-28 03:39:23 +00002872 return Error(Label.Loc, "expected basic block name in blockaddress");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002873
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002874 // Try to find the function (but skip it if it's forward-referenced).
2875 GlobalValue *GV = nullptr;
2876 if (Fn.Kind == ValID::t_GlobalID) {
2877 if (Fn.UIntVal < NumberedVals.size())
2878 GV = NumberedVals[Fn.UIntVal];
2879 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2880 GV = M->getNamedValue(Fn.StrVal);
2881 }
2882 Function *F = nullptr;
2883 if (GV) {
2884 // Confirm that it's actually a function with a definition.
2885 if (!isa<Function>(GV))
2886 return Error(Fn.Loc, "expected function name in blockaddress");
2887 F = cast<Function>(GV);
2888 if (F->isDeclaration())
2889 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2890 }
2891
2892 if (!F) {
2893 // Make a global variable as a placeholder for this reference.
David Blaikieb9cc6592015-03-04 01:40:07 +00002894 GlobalValue *&FwdRef =
David Blaikie871b4112015-08-03 20:55:00 +00002895 ForwardRefBlockAddresses.insert(std::make_pair(
2896 std::move(Fn),
2897 std::map<ValID, GlobalValue *>()))
David Blaikieb9cc6592015-03-04 01:40:07 +00002898 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2899 .first->second;
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002900 if (!FwdRef)
2901 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2902 GlobalValue::InternalLinkage, nullptr, "");
2903 ID.ConstantVal = FwdRef;
2904 ID.Kind = ValID::t_Constant;
2905 return false;
2906 }
2907
2908 // We found the function; now find the basic block. Don't use PFS, since we
2909 // might be inside a constant expression.
2910 BasicBlock *BB;
2911 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2912 if (Label.Kind == ValID::t_LocalID)
2913 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2914 else
2915 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2916 if (!BB)
2917 return Error(Label.Loc, "referenced value is not a basic block");
2918 } else {
2919 if (Label.Kind == ValID::t_LocalID)
2920 return Error(Label.Loc, "cannot take address of numeric label after "
2921 "the function is defined");
2922 BB = dyn_cast_or_null<BasicBlock>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002923 F->getValueSymbolTable()->lookup(Label.StrVal));
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00002924 if (!BB)
2925 return Error(Label.Loc, "referenced value is not a basic block");
2926 }
2927
2928 ID.ConstantVal = BlockAddress::get(F, BB);
Chris Lattner3432c622009-10-28 03:39:23 +00002929 ID.Kind = ValID::t_Constant;
2930 return false;
2931 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002932
Chris Lattnerac161bf2009-01-02 07:01:27 +00002933 case lltok::kw_trunc:
2934 case lltok::kw_zext:
2935 case lltok::kw_sext:
2936 case lltok::kw_fptrunc:
2937 case lltok::kw_fpext:
2938 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002939 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002940 case lltok::kw_uitofp:
2941 case lltok::kw_sitofp:
2942 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002943 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00002944 case lltok::kw_inttoptr:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002945 case lltok::kw_ptrtoint: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00002946 unsigned Opc = Lex.getUIntVal();
Craig Topper2617dcc2014-04-15 06:32:26 +00002947 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00002948 Constant *SrcVal;
2949 Lex.Lex();
2950 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2951 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman0b5d0422009-06-15 21:52:11 +00002952 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00002953 ParseType(DestTy) ||
2954 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2955 return true;
2956 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2957 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00002958 getTypeString(SrcVal->getType()) + "' to '" +
2959 getTypeString(DestTy) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002960 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Anderson02a9da32009-07-01 23:57:11 +00002961 SrcVal, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002962 ID.Kind = ValID::t_Constant;
2963 return false;
2964 }
2965 case lltok::kw_extractvalue: {
2966 Lex.Lex();
2967 Constant *Val;
2968 SmallVector<unsigned, 4> Indices;
2969 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2970 ParseGlobalTypeAndValue(Val) ||
2971 ParseIndexList(Indices) ||
2972 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2973 return true;
Devang Patel1cb51162009-11-03 19:06:07 +00002974
Chris Lattner392be582010-02-12 20:49:41 +00002975 if (!Val->getType()->isAggregateType())
2976 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foad57aa6362011-07-13 10:26:04 +00002977 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00002978 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00002979 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00002980 ID.Kind = ValID::t_Constant;
2981 return false;
2982 }
2983 case lltok::kw_insertvalue: {
2984 Lex.Lex();
2985 Constant *Val0, *Val1;
2986 SmallVector<unsigned, 4> Indices;
2987 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2988 ParseGlobalTypeAndValue(Val0) ||
2989 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2990 ParseGlobalTypeAndValue(Val1) ||
2991 ParseIndexList(Indices) ||
2992 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2993 return true;
Chris Lattner392be582010-02-12 20:49:41 +00002994 if (!Val0->getType()->isAggregateType())
2995 return Error(ID.Loc, "insertvalue operand must be aggregate type");
David Majnemereba692d2015-02-23 07:13:52 +00002996 Type *IndexedType =
2997 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2998 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00002999 return Error(ID.Loc, "invalid indices for insertvalue");
David Majnemereba692d2015-02-23 07:13:52 +00003000 if (IndexedType != Val1->getType())
3001 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3002 getTypeString(Val1->getType()) +
3003 "' instead of '" + getTypeString(IndexedType) +
3004 "'");
Jay Foad57aa6362011-07-13 10:26:04 +00003005 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003006 ID.Kind = ValID::t_Constant;
3007 return false;
3008 }
3009 case lltok::kw_icmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003010 case lltok::kw_fcmp: {
Chris Lattnerac161bf2009-01-02 07:01:27 +00003011 unsigned PredVal, Opc = Lex.getUIntVal();
3012 Constant *Val0, *Val1;
3013 Lex.Lex();
3014 if (ParseCmpPredicate(PredVal, Opc) ||
3015 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3016 ParseGlobalTypeAndValue(Val0) ||
3017 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3018 ParseGlobalTypeAndValue(Val1) ||
3019 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3020 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003021
Chris Lattnerac161bf2009-01-02 07:01:27 +00003022 if (Val0->getType() != Val1->getType())
3023 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003024
Chris Lattnerac161bf2009-01-02 07:01:27 +00003025 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003026
Chris Lattnerac161bf2009-01-02 07:01:27 +00003027 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00003028 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003029 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003030 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003031 } else {
3032 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003033 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00003034 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003035 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003036 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003037 }
3038 ID.Kind = ValID::t_Constant;
3039 return false;
3040 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003041
Chris Lattnerac161bf2009-01-02 07:01:27 +00003042 // Binary Operators.
3043 case lltok::kw_add:
Dan Gohmana5b96452009-06-04 22:49:04 +00003044 case lltok::kw_fadd:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003045 case lltok::kw_sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00003046 case lltok::kw_fsub:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003047 case lltok::kw_mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00003048 case lltok::kw_fmul:
Chris Lattnerac161bf2009-01-02 07:01:27 +00003049 case lltok::kw_udiv:
3050 case lltok::kw_sdiv:
3051 case lltok::kw_fdiv:
3052 case lltok::kw_urem:
3053 case lltok::kw_srem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003054 case lltok::kw_frem:
3055 case lltok::kw_shl:
3056 case lltok::kw_lshr:
3057 case lltok::kw_ashr: {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003058 bool NUW = false;
3059 bool NSW = false;
3060 bool Exact = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003061 unsigned Opc = Lex.getUIntVal();
3062 Constant *Val0, *Val1;
3063 Lex.Lex();
Dan Gohman9c7f8082009-07-27 16:11:46 +00003064 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnera676c0f2011-02-07 16:40:21 +00003065 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3066 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003067 if (EatIfPresent(lltok::kw_nuw))
3068 NUW = true;
3069 if (EatIfPresent(lltok::kw_nsw)) {
3070 NSW = true;
3071 if (EatIfPresent(lltok::kw_nuw))
3072 NUW = true;
3073 }
Chris Lattnera676c0f2011-02-07 16:40:21 +00003074 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3075 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003076 if (EatIfPresent(lltok::kw_exact))
3077 Exact = true;
3078 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00003079 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3080 ParseGlobalTypeAndValue(Val0) ||
3081 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3082 ParseGlobalTypeAndValue(Val1) ||
3083 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3084 return true;
3085 if (Val0->getType() != Val1->getType())
3086 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003087 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman9c7f8082009-07-27 16:11:46 +00003088 if (NUW)
3089 return Error(ModifierLoc, "nuw only applies to integer operations");
3090 if (NSW)
3091 return Error(ModifierLoc, "nsw only applies to integer operations");
3092 }
Dan Gohmana2414ea2010-05-03 22:44:19 +00003093 // Check that the type is valid for the operator.
3094 switch (Opc) {
3095 case Instruction::Add:
3096 case Instruction::Sub:
3097 case Instruction::Mul:
3098 case Instruction::UDiv:
3099 case Instruction::SDiv:
3100 case Instruction::URem:
3101 case Instruction::SRem:
Chris Lattnera676c0f2011-02-07 16:40:21 +00003102 case Instruction::Shl:
3103 case Instruction::AShr:
3104 case Instruction::LShr:
Dan Gohmana2414ea2010-05-03 22:44:19 +00003105 if (!Val0->getType()->isIntOrIntVectorTy())
3106 return Error(ID.Loc, "constexpr requires integer operands");
3107 break;
3108 case Instruction::FAdd:
3109 case Instruction::FSub:
3110 case Instruction::FMul:
3111 case Instruction::FDiv:
3112 case Instruction::FRem:
3113 if (!Val0->getType()->isFPOrFPVectorTy())
3114 return Error(ID.Loc, "constexpr requires fp operands");
3115 break;
3116 default: llvm_unreachable("Unknown binary operator!");
3117 }
Dan Gohman1b849082009-09-07 23:54:19 +00003118 unsigned Flags = 0;
3119 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3120 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003121 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohman1b849082009-09-07 23:54:19 +00003122 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman9c7f8082009-07-27 16:11:46 +00003123 ID.ConstantVal = C;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003124 ID.Kind = ValID::t_Constant;
3125 return false;
3126 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003127
Chris Lattnerac161bf2009-01-02 07:01:27 +00003128 // Logical Operations
Chris Lattnerac161bf2009-01-02 07:01:27 +00003129 case lltok::kw_and:
3130 case lltok::kw_or:
3131 case lltok::kw_xor: {
3132 unsigned Opc = Lex.getUIntVal();
3133 Constant *Val0, *Val1;
3134 Lex.Lex();
3135 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3136 ParseGlobalTypeAndValue(Val0) ||
3137 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3138 ParseGlobalTypeAndValue(Val1) ||
3139 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3140 return true;
3141 if (Val0->getType() != Val1->getType())
3142 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sands9dff9be2010-02-15 16:12:20 +00003143 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00003144 return Error(ID.Loc,
3145 "constexpr requires integer or integer vector operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003146 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003147 ID.Kind = ValID::t_Constant;
3148 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003149 }
3150
Chris Lattnerac161bf2009-01-02 07:01:27 +00003151 case lltok::kw_getelementptr:
3152 case lltok::kw_shufflevector:
3153 case lltok::kw_insertelement:
3154 case lltok::kw_extractelement:
3155 case lltok::kw_select: {
3156 unsigned Opc = Lex.getUIntVal();
3157 SmallVector<Constant*, 16> Elts;
Dan Gohman1639c392009-07-27 21:53:46 +00003158 bool InBounds = false;
David Blaikief72d05b2015-03-13 18:20:45 +00003159 Type *Ty;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003160 Lex.Lex();
David Blaikief72d05b2015-03-13 18:20:45 +00003161
Dan Gohman1639c392009-07-27 21:53:46 +00003162 if (Opc == Instruction::GetElementPtr)
Dan Gohman16cbbe42009-07-29 15:58:36 +00003163 InBounds = EatIfPresent(lltok::kw_inbounds);
David Blaikief72d05b2015-03-13 18:20:45 +00003164
3165 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3166 return true;
3167
3168 LocTy ExplicitTypeLoc = Lex.getLoc();
3169 if (Opc == Instruction::GetElementPtr) {
3170 if (ParseType(Ty) ||
3171 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3172 return true;
3173 }
3174
Peter Collingbourned93620b2016-11-10 22:34:55 +00003175 Optional<unsigned> InRangeOp;
3176 if (ParseGlobalValueVector(
3177 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00003178 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3179 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003180
Chris Lattnerac161bf2009-01-02 07:01:27 +00003181 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00003182 if (Elts.size() == 0 ||
3183 !Elts[0]->getType()->getScalarType()->isPointerTy())
David Majnemer00303b62015-02-22 23:14:52 +00003184 return Error(ID.Loc, "base of getelementptr must be a pointer");
3185
3186 Type *BaseType = Elts[0]->getType();
3187 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
David Blaikief72d05b2015-03-13 18:20:45 +00003188 if (Ty != BasePointerType->getElementType())
3189 return Error(
3190 ExplicitTypeLoc,
3191 "explicit pointee type doesn't match operand's pointee type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003192
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003193 unsigned GEPWidth =
3194 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3195
Jay Foaded8db7d2011-07-21 14:31:17 +00003196 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
David Majnemer00303b62015-02-22 23:14:52 +00003197 for (Constant *Val : Indices) {
3198 Type *ValTy = Val->getType();
3199 if (!ValTy->getScalarType()->isIntegerTy())
3200 return Error(ID.Loc, "getelementptr index must be an integer");
David Majnemer00303b62015-02-22 23:14:52 +00003201 if (ValTy->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00003202 unsigned ValNumEl = ValTy->getVectorNumElements();
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003203 if (GEPWidth && (ValNumEl != GEPWidth))
David Majnemer00303b62015-02-22 23:14:52 +00003204 return Error(
3205 ID.Loc,
3206 "getelementptr vector index has a wrong number of elements");
Michael Kuperstein88f15ee2016-12-21 18:29:47 +00003207 // GEPWidth may have been unknown because the base is a scalar,
3208 // but it is known now.
3209 GEPWidth = ValNumEl;
David Majnemer00303b62015-02-22 23:14:52 +00003210 }
3211 }
3212
Craig Toppere3dcce92015-08-01 22:20:21 +00003213 SmallPtrSet<Type*, 4> Visited;
David Blaikiee169e822015-04-22 16:37:35 +00003214 if (!Indices.empty() && !Ty->isSized(&Visited))
David Majnemer00303b62015-02-22 23:14:52 +00003215 return Error(ID.Loc, "base element of getelementptr must be sized");
3216
David Blaikie4a2e73b2015-04-02 18:55:32 +00003217 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
David Majnemer00303b62015-02-22 23:14:52 +00003218 return Error(ID.Loc, "invalid getelementptr indices");
Peter Collingbourned93620b2016-11-10 22:34:55 +00003219
3220 if (InRangeOp) {
3221 if (*InRangeOp == 0)
3222 return Error(ID.Loc,
3223 "inrange keyword may not appear on pointer operand");
3224 --*InRangeOp;
3225 }
3226
3227 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3228 InBounds, InRangeOp);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003229 } else if (Opc == Instruction::Select) {
3230 if (Elts.size() != 3)
3231 return Error(ID.Loc, "expected three operands to select");
3232 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3233 Elts[2]))
3234 return Error(ID.Loc, Reason);
Owen Anderson487375e2009-07-29 18:55:55 +00003235 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003236 } else if (Opc == Instruction::ShuffleVector) {
3237 if (Elts.size() != 3)
3238 return Error(ID.Loc, "expected three operands to shufflevector");
3239 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3240 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Anderson02a9da32009-07-01 23:57:11 +00003241 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003242 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003243 } else if (Opc == Instruction::ExtractElement) {
3244 if (Elts.size() != 2)
3245 return Error(ID.Loc, "expected two operands to extractelement");
3246 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3247 return Error(ID.Loc, "invalid extractelement operands");
Owen Anderson487375e2009-07-29 18:55:55 +00003248 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003249 } else {
3250 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3251 if (Elts.size() != 3)
3252 return Error(ID.Loc, "expected three operands to insertelement");
3253 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3254 return Error(ID.Loc, "invalid insertelement operands");
Owen Anderson02a9da32009-07-01 23:57:11 +00003255 ID.ConstantVal =
Owen Anderson487375e2009-07-29 18:55:55 +00003256 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerac161bf2009-01-02 07:01:27 +00003257 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003258
Chris Lattnerac161bf2009-01-02 07:01:27 +00003259 ID.Kind = ValID::t_Constant;
3260 return false;
3261 }
3262 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003263
Chris Lattnerac161bf2009-01-02 07:01:27 +00003264 Lex.Lex();
3265 return false;
3266}
3267
3268/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattner229907c2011-07-18 04:54:35 +00003269bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003270 C = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003271 ValID ID;
Craig Topper2617dcc2014-04-15 06:32:26 +00003272 Value *V = nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003273 bool Parsed = ParseValID(ID) ||
Craig Topper2617dcc2014-04-15 06:32:26 +00003274 ConvertValIDToValue(Ty, ID, V, nullptr);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003275 if (V && !(C = dyn_cast<Constant>(V)))
3276 return Error(ID.Loc, "global values must be constants");
3277 return Parsed;
Chris Lattnerac161bf2009-01-02 07:01:27 +00003278}
3279
Victor Hernandez9d75c962010-01-11 22:31:58 +00003280bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003281 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003282 return ParseType(Ty) ||
3283 ParseGlobalValue(Ty, V);
Victor Hernandez9d75c962010-01-11 22:31:58 +00003284}
3285
Rafael Espindola83a362c2015-01-06 22:55:16 +00003286bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
David Majnemerdad0a642014-06-27 18:19:56 +00003287 C = nullptr;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003288
3289 LocTy KwLoc = Lex.getLoc();
David Majnemerdad0a642014-06-27 18:19:56 +00003290 if (!EatIfPresent(lltok::kw_comdat))
3291 return false;
Rafael Espindola83a362c2015-01-06 22:55:16 +00003292
3293 if (EatIfPresent(lltok::lparen)) {
3294 if (Lex.getKind() != lltok::ComdatVar)
3295 return TokError("expected comdat variable");
3296 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3297 Lex.Lex();
3298 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3299 return true;
3300 } else {
3301 if (GlobalName.empty())
3302 return TokError("comdat cannot be unnamed");
3303 C = getComdat(GlobalName, KwLoc);
3304 }
3305
David Majnemerdad0a642014-06-27 18:19:56 +00003306 return false;
3307}
3308
Victor Hernandez9d75c962010-01-11 22:31:58 +00003309/// ParseGlobalValueVector
3310/// ::= /*empty*/
Peter Collingbourned93620b2016-11-10 22:34:55 +00003311/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3312bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3313 Optional<unsigned> *InRangeOp) {
Victor Hernandez9d75c962010-01-11 22:31:58 +00003314 // Empty list.
3315 if (Lex.getKind() == lltok::rbrace ||
3316 Lex.getKind() == lltok::rsquare ||
3317 Lex.getKind() == lltok::greater ||
3318 Lex.getKind() == lltok::rparen)
3319 return false;
3320
Peter Collingbourned93620b2016-11-10 22:34:55 +00003321 do {
3322 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3323 *InRangeOp = Elts.size();
Victor Hernandez9d75c962010-01-11 22:31:58 +00003324
Peter Collingbourned93620b2016-11-10 22:34:55 +00003325 Constant *C;
Victor Hernandez9d75c962010-01-11 22:31:58 +00003326 if (ParseGlobalTypeAndValue(C)) return true;
3327 Elts.push_back(C);
Peter Collingbourned93620b2016-11-10 22:34:55 +00003328 } while (EatIfPresent(lltok::comma));
Victor Hernandez9d75c962010-01-11 22:31:58 +00003329
3330 return false;
3331}
3332
Duncan P. N. Exon Smith58ef9d12015-01-12 21:23:11 +00003333bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003334 SmallVector<Metadata *, 16> Elts;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003335 if (ParseMDNodeVector(Elts))
Dan Gohmanc828c542010-08-24 02:24:03 +00003336 return true;
3337
Duncan P. N. Exon Smith0b31dd12015-01-12 22:27:39 +00003338 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
Dan Gohmanc828c542010-08-24 02:24:03 +00003339 return false;
3340}
3341
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003342/// MDNode:
3343/// ::= !{ ... }
3344/// ::= !7
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003345/// ::= !DILocation(...)
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003346bool LLParser::ParseMDNode(MDNode *&N) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003347 if (Lex.getKind() == lltok::MetadataVar)
3348 return ParseSpecializedMDNode(N);
3349
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00003350 return ParseToken(lltok::exclaim, "expected '!' here") ||
3351 ParseMDNodeTail(N);
3352}
3353
3354bool LLParser::ParseMDNodeTail(MDNode *&N) {
3355 // !{ ... }
3356 if (Lex.getKind() == lltok::lbrace)
3357 return ParseMDTuple(N);
3358
3359 // !42
3360 return ParseMDNodeID(N);
3361}
3362
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003363namespace {
3364
3365/// Structure to represent an optional metadata field.
3366template <class FieldTy> struct MDFieldImpl {
3367 typedef MDFieldImpl ImplTy;
3368 FieldTy Val;
3369 bool Seen;
3370
3371 void assign(FieldTy Val) {
3372 Seen = true;
3373 this->Val = std::move(Val);
3374 }
3375
3376 explicit MDFieldImpl(FieldTy Default)
3377 : Val(std::move(Default)), Seen(false) {}
3378};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003379
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003380struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3381 uint64_t Max;
3382
3383 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3384 : ImplTy(Default), Max(Max) {}
3385};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003386
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003387struct LineField : public MDUnsignedField {
Duncan P. N. Exon Smithaf677eb2015-02-06 22:50:13 +00003388 LineField() : MDUnsignedField(0, UINT32_MAX) {}
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003389};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003390
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003391struct ColumnField : public MDUnsignedField {
3392 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3393};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003394
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003395struct DwarfTagField : public MDUnsignedField {
Duncan P. N. Exon Smitha81f7e12015-02-06 22:29:35 +00003396 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003397 DwarfTagField(dwarf::Tag DefaultTag)
3398 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003399};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003400
Amjad Abouda9bcf162015-12-10 12:56:35 +00003401struct DwarfMacinfoTypeField : public MDUnsignedField {
3402 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3403 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3404 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3405};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003406
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003407struct DwarfAttEncodingField : public MDUnsignedField {
3408 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3409};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003410
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003411struct DwarfVirtualityField : public MDUnsignedField {
3412 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3413};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003414
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003415struct DwarfLangField : public MDUnsignedField {
3416 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3417};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003418
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003419struct DwarfCCField : public MDUnsignedField {
3420 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3421};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003422
Adrian Prantlb939a252016-03-31 23:56:58 +00003423struct EmissionKindField : public MDUnsignedField {
3424 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3425};
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003426
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003427struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3428 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003429};
3430
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003431struct MDSignedField : public MDFieldImpl<int64_t> {
3432 int64_t Min;
3433 int64_t Max;
3434
3435 MDSignedField(int64_t Default = 0)
3436 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3437 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3438 : ImplTy(Default), Min(Min), Max(Max) {}
3439};
3440
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003441struct MDBoolField : public MDFieldImpl<bool> {
3442 MDBoolField(bool Default = false) : ImplTy(Default) {}
3443};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003444
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003445struct MDField : public MDFieldImpl<Metadata *> {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003446 bool AllowNull;
3447
3448 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003449};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003450
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003451struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3452 MDConstant() : ImplTy(nullptr) {}
3453};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003454
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003455struct MDStringField : public MDFieldImpl<MDString *> {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003456 bool AllowEmpty;
3457 MDStringField(bool AllowEmpty = true)
3458 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003459};
Eugene Zelenko1804a772016-08-25 00:45:04 +00003460
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003461struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3462 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3463};
3464
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003465struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3466 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3467 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3468};
3469
Eugene Zelenko1804a772016-08-25 00:45:04 +00003470} // end anonymous namespace
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003471
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003472namespace llvm {
3473
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003474template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003475bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003476 MDUnsignedField &Result) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003477 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3478 return TokError("expected unsigned integer");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003479
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003480 auto &U = Lex.getAPSIntVal();
3481 if (U.ugt(Result.Max))
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003482 return TokError("value for '" + Name + "' too large, limit is " +
3483 Twine(Result.Max));
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003484 Result.assign(U.getZExtValue());
3485 assert(Result.Val <= Result.Max && "Expected value in range");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003486 Lex.Lex();
3487 return false;
3488}
3489
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003490template <>
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003491bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3492 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3493}
3494template <>
3495bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3496 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3497}
3498
3499template <>
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003500bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3501 if (Lex.getKind() == lltok::APSInt)
Duncan P. N. Exon Smith39b10c22015-02-04 21:57:52 +00003502 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003503
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003504 if (Lex.getKind() != lltok::DwarfTag)
3505 return TokError("expected DWARF tag");
3506
3507 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3508 if (Tag == dwarf::DW_TAG_invalid)
3509 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
Duncan P. N. Exon Smithfad631a2015-02-04 22:02:18 +00003510 assert(Tag <= Result.Max && "Expected valid DWARF tag");
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003511
3512 Result.assign(Tag);
3513 Lex.Lex();
3514 return false;
3515}
3516
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003517template <>
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003518bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Amjad Abouda9bcf162015-12-10 12:56:35 +00003519 DwarfMacinfoTypeField &Result) {
3520 if (Lex.getKind() == lltok::APSInt)
3521 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3522
3523 if (Lex.getKind() != lltok::DwarfMacinfo)
3524 return TokError("expected DWARF macinfo type");
3525
3526 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3527 if (Macinfo == dwarf::DW_MACINFO_invalid)
3528 return TokError(
3529 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3530 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3531
3532 Result.assign(Macinfo);
3533 Lex.Lex();
3534 return false;
3535}
3536
3537template <>
3538bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003539 DwarfVirtualityField &Result) {
3540 if (Lex.getKind() == lltok::APSInt)
3541 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3542
3543 if (Lex.getKind() != lltok::DwarfVirtuality)
3544 return TokError("expected DWARF virtuality code");
3545
3546 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
Peter Collingbournea1f86252016-03-17 23:58:03 +00003547 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00003548 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3549 Lex.getStrVal() + "'");
3550 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3551 Result.assign(Virtuality);
3552 Lex.Lex();
3553 return false;
3554}
3555
3556template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003557bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3558 if (Lex.getKind() == lltok::APSInt)
3559 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3560
3561 if (Lex.getKind() != lltok::DwarfLang)
3562 return TokError("expected DWARF language");
3563
3564 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3565 if (!Lang)
3566 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3567 "'");
3568 assert(Lang <= Result.Max && "Expected valid DWARF language");
3569 Result.assign(Lang);
3570 Lex.Lex();
3571 return false;
3572}
3573
3574template <>
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003575bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3576 if (Lex.getKind() == lltok::APSInt)
3577 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3578
3579 if (Lex.getKind() != lltok::DwarfCC)
3580 return TokError("expected DWARF calling convention");
3581
3582 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3583 if (!CC)
3584 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3585 "'");
3586 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3587 Result.assign(CC);
3588 Lex.Lex();
3589 return false;
3590}
3591
3592template <>
Adrian Prantlb939a252016-03-31 23:56:58 +00003593bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3594 if (Lex.getKind() == lltok::APSInt)
3595 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3596
3597 if (Lex.getKind() != lltok::EmissionKind)
3598 return TokError("expected emission kind");
3599
3600 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3601 if (!Kind)
3602 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3603 "'");
3604 assert(*Kind <= Result.Max && "Expected valid emission kind");
3605 Result.assign(*Kind);
3606 Lex.Lex();
3607 return false;
3608}
3609
3610template <>
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003611bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003612 DwarfAttEncodingField &Result) {
3613 if (Lex.getKind() == lltok::APSInt)
3614 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3615
3616 if (Lex.getKind() != lltok::DwarfAttEncoding)
3617 return TokError("expected DWARF type attribute encoding");
3618
3619 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3620 if (!Encoding)
3621 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3622 Lex.getStrVal() + "'");
3623 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3624 Result.assign(Encoding);
3625 Lex.Lex();
3626 return false;
3627}
3628
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003629/// DIFlagField
3630/// ::= uint32
3631/// ::= DIFlagVector
3632/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3633template <>
3634bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003635
3636 // Parser for a single flag.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003637 auto parseFlag = [&](DINode::DIFlags &Val) {
3638 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3639 uint32_t TempVal = static_cast<uint32_t>(Val);
3640 bool Res = ParseUInt32(TempVal);
3641 Val = static_cast<DINode::DIFlags>(TempVal);
3642 return Res;
3643 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003644
3645 if (Lex.getKind() != lltok::DIFlag)
3646 return TokError("expected debug info flag");
3647
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003648 Val = DINode::getFlag(Lex.getStrVal());
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003649 if (!Val)
3650 return TokError(Twine("invalid debug info flag flag '") +
3651 Lex.getStrVal() + "'");
3652 Lex.Lex();
3653 return false;
3654 };
3655
3656 // Parse the flags and combine them together.
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003657 DINode::DIFlags Combined = DINode::FlagZero;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003658 do {
Leny Kholodov5fcc4182016-09-06 10:46:28 +00003659 DINode::DIFlags Val;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003660 if (parseFlag(Val))
3661 return true;
3662 Combined |= Val;
3663 } while (EatIfPresent(lltok::bar));
3664
3665 Result.assign(Combined);
3666 return false;
3667}
3668
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003669template <>
3670bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003671 MDSignedField &Result) {
3672 if (Lex.getKind() != lltok::APSInt)
3673 return TokError("expected signed integer");
3674
3675 auto &S = Lex.getAPSIntVal();
3676 if (S < Result.Min)
3677 return TokError("value for '" + Name + "' too small, limit is " +
3678 Twine(Result.Min));
3679 if (S > Result.Max)
3680 return TokError("value for '" + Name + "' too large, limit is " +
3681 Twine(Result.Max));
3682 Result.assign(S.getExtValue());
3683 assert(Result.Val >= Result.Min && "Expected value in range");
3684 assert(Result.Val <= Result.Max && "Expected value in range");
3685 Lex.Lex();
3686 return false;
3687}
3688
3689template <>
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003690bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3691 switch (Lex.getKind()) {
3692 default:
3693 return TokError("expected 'true' or 'false'");
3694 case lltok::kw_true:
3695 Result.assign(true);
3696 break;
3697 case lltok::kw_false:
3698 Result.assign(false);
3699 break;
3700 }
3701 Lex.Lex();
3702 return false;
3703}
3704
3705template <>
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003706bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003707 if (Lex.getKind() == lltok::kw_null) {
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003708 if (!Result.AllowNull)
3709 return TokError("'" + Name + "' cannot be null");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00003710 Lex.Lex();
3711 Result.assign(nullptr);
3712 return false;
3713 }
3714
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003715 Metadata *MD;
3716 if (ParseMetadata(MD, nullptr))
3717 return true;
3718
3719 Result.assign(MD);
3720 return false;
3721}
3722
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003723template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003724bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003725 LocTy ValueLoc = Lex.getLoc();
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003726 std::string S;
3727 if (ParseStringConstant(S))
3728 return true;
3729
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00003730 if (!Result.AllowEmpty && S.empty())
3731 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3732
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00003733 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003734 return false;
3735}
3736
Duncan P. N. Exon Smith077c0312015-02-04 22:05:21 +00003737template <>
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003738bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3739 SmallVector<Metadata *, 4> MDs;
3740 if (ParseMDNodeVector(MDs))
3741 return true;
3742
3743 Result.assign(std::move(MDs));
3744 return false;
3745}
3746
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003747template <>
3748bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3749 ChecksumKindField &Result) {
3750 if (Lex.getKind() != lltok::ChecksumKind)
3751 return TokError(
3752 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3753
3754 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3755
3756 Result.assign(CSKind);
3757 Lex.Lex();
3758 return false;
3759}
3760
Duncan P. N. Exon Smith2f09c462015-02-04 22:13:28 +00003761} // end namespace llvm
3762
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003763template <class ParserTy>
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003764bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003765 do {
3766 if (Lex.getKind() != lltok::LabelStr)
3767 return TokError("expected field label here");
3768
3769 if (parseField())
3770 return true;
3771 } while (EatIfPresent(lltok::comma));
3772
Duncan P. N. Exon Smith66ca92e2015-01-19 23:39:32 +00003773 return false;
3774}
3775
3776template <class ParserTy>
3777bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3778 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3779 Lex.Lex();
3780
3781 if (ParseToken(lltok::lparen, "expected '(' here"))
3782 return true;
3783 if (Lex.getKind() != lltok::rparen)
3784 if (ParseMDFieldsImplBody(parseField))
3785 return true;
3786
Duncan P. N. Exon Smith13890af2015-01-19 23:32:36 +00003787 ClosingLoc = Lex.getLoc();
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003788 return ParseToken(lltok::rparen, "expected ')' here");
3789}
3790
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003791template <class FieldTy>
3792bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3793 if (Result.Seen)
3794 return TokError("field '" + Name + "' cannot be specified more than once");
3795
3796 LocTy Loc = Lex.getLoc();
3797 Lex.Lex();
3798 return ParseMDField(Loc, Name, Result);
3799}
3800
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003801bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3802 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003803
3804#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003805 if (Lex.getStrVal() == #CLASS) \
3806 return Parse##CLASS(N, IsDistinct);
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003807#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003808
3809 return TokError("expected metadata type");
3810}
3811
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003812#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3813#define NOP_FIELD(NAME, TYPE, INIT)
3814#define REQUIRE_FIELD(NAME, TYPE, INIT) \
3815 if (!NAME.Seen) \
3816 return Error(ClosingLoc, "missing required field '" #NAME "'");
3817#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
Duncan P. N. Exon Smitha7477282015-01-20 02:42:29 +00003818 if (Lex.getStrVal() == #NAME) \
3819 return ParseMDField(#NAME, NAME);
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003820#define PARSE_MD_FIELDS() \
3821 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3822 do { \
3823 LocTy ClosingLoc; \
3824 if (ParseMDFieldsImpl([&]() -> bool { \
3825 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3826 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3827 }, ClosingLoc)) \
3828 return true; \
3829 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3830 } while (false)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003831#define GET_OR_DISTINCT(CLASS, ARGS) \
3832 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003833
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003834/// ParseDILocationFields:
3835/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3836bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003837#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith9c93dc62015-02-04 22:59:18 +00003838 OPTIONAL(line, LineField, ); \
3839 OPTIONAL(column, ColumnField, ); \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00003840 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00003841 OPTIONAL(inlinedAt, MDField, );
3842 PARSE_MD_FIELDS();
3843#undef VISIT_MD_FIELDS
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003844
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00003845 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003846 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00003847 return false;
3848}
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003849
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003850/// ParseGenericDINode:
3851/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3852bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003853#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith97486072015-02-03 21:56:01 +00003854 REQUIRED(tag, DwarfTagField, ); \
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003855 OPTIONAL(header, MDStringField, ); \
3856 OPTIONAL(operands, MDFieldList, );
3857 PARSE_MD_FIELDS();
3858#undef VISIT_MD_FIELDS
3859
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003860 Result = GET_OR_DISTINCT(GenericDINode,
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00003861 (Context, tag.Val, header.Val, operands.Val));
3862 return false;
3863}
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003864
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003865/// ParseDISubrange:
3866/// ::= !DISubrange(count: 30, lowerBound: 2)
3867bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003868#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith5c9a1772015-02-18 23:17:51 +00003869 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003870 OPTIONAL(lowerBound, MDSignedField, );
3871 PARSE_MD_FIELDS();
3872#undef VISIT_MD_FIELDS
3873
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003874 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003875 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003876}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00003877
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003878/// ParseDIEnumerator:
3879/// ::= !DIEnumerator(value: 30, name: "SomeKind")
3880bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003881#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithcd8fb602015-02-18 21:16:33 +00003882 REQUIRED(name, MDStringField, ); \
3883 REQUIRED(value, MDSignedField, );
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003884 PARSE_MD_FIELDS();
3885#undef VISIT_MD_FIELDS
3886
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003887 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003888 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003889}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00003890
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003891/// ParseDIBasicType:
3892/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3893bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003894#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00003895 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003896 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003897 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003898 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithcd6636c2015-02-13 01:17:35 +00003899 OPTIONAL(encoding, DwarfAttEncodingField, );
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003900 PARSE_MD_FIELDS();
3901#undef VISIT_MD_FIELDS
3902
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003903 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003904 align.Val, encoding.Val));
3905 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003906}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00003907
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003908/// ParseDIDerivedType:
3909/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003910/// line: 7, scope: !1, baseType: !2, size: 32,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003911/// align: 32, offset: 0, flags: 0, extraData: !3,
3912/// dwarfAddressSpace: 3)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003913bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003914#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3915 REQUIRED(tag, DwarfTagField, ); \
3916 OPTIONAL(name, MDStringField, ); \
3917 OPTIONAL(file, MDField, ); \
3918 OPTIONAL(line, LineField, ); \
3919 OPTIONAL(scope, MDField, ); \
3920 REQUIRED(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003921 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003922 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003923 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003924 OPTIONAL(flags, DIFlagField, ); \
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003925 OPTIONAL(extraData, MDField, ); \
3926 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003927 PARSE_MD_FIELDS();
3928#undef VISIT_MD_FIELDS
3929
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003930 Optional<unsigned> DWARFAddressSpace;
3931 if (dwarfAddressSpace.Val != UINT32_MAX)
3932 DWARFAddressSpace = dwarfAddressSpace.Val;
3933
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003934 Result = GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003935 (Context, tag.Val, name.Val, file.Val, line.Val,
3936 scope.Val, baseType.Val, size.Val, align.Val,
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00003937 offset.Val, DWARFAddressSpace, flags.Val,
3938 extraData.Val));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003939 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003940}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003941
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003942bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003943#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3944 REQUIRED(tag, DwarfTagField, ); \
3945 OPTIONAL(name, MDStringField, ); \
3946 OPTIONAL(file, MDField, ); \
3947 OPTIONAL(line, LineField, ); \
3948 OPTIONAL(scope, MDField, ); \
3949 OPTIONAL(baseType, MDField, ); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003950 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
Victor Leschuk197aa312016-10-18 14:31:22 +00003951 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
Duncan P. N. Exon Smithd34db172015-02-19 23:56:07 +00003952 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003953 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003954 OPTIONAL(elements, MDField, ); \
Duncan P. N. Exon Smithaece2dc2015-02-13 01:21:25 +00003955 OPTIONAL(runtimeLang, DwarfLangField, ); \
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003956 OPTIONAL(vtableHolder, MDField, ); \
3957 OPTIONAL(templateParams, MDField, ); \
3958 OPTIONAL(identifier, MDStringField, );
3959 PARSE_MD_FIELDS();
3960#undef VISIT_MD_FIELDS
3961
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00003962 // If this has an identifier try to build an ODR type.
3963 if (identifier.Val)
3964 if (auto *CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00003965 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3966 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3967 elements.Val, runtimeLang.Val, vtableHolder.Val,
3968 templateParams.Val)) {
3969 Result = CT;
3970 return false;
3971 }
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00003972
3973 // Create a new node, and save it in the context if it belongs in the type
3974 // map.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003975 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003976 DICompositeType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003977 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3978 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3979 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3980 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003981}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00003982
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003983bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003984#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00003985 OPTIONAL(flags, DIFlagField, ); \
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003986 OPTIONAL(cc, DwarfCCField, ); \
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003987 REQUIRED(types, MDField, );
3988 PARSE_MD_FIELDS();
3989#undef VISIT_MD_FIELDS
3990
Reid Klecknerde3d8b52016-06-08 20:34:29 +00003991 Result = GET_OR_DISTINCT(DISubroutineType,
3992 (Context, flags.Val, cc.Val, types.Val));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00003993 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00003994}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00003995
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003996/// ParseDIFileType:
Amjad Aboud7faeecc2016-12-25 10:12:09 +00003997/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
3998/// checksumkind: CSK_MD5,
3999/// checksum: "000102030405060708090a0b0c0d0e0f")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004000bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004001#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4002 REQUIRED(filename, MDStringField, ); \
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004003 REQUIRED(directory, MDStringField, ); \
4004 OPTIONAL(checksumkind, ChecksumKindField, ); \
4005 OPTIONAL(checksum, MDStringField, );
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004006 PARSE_MD_FIELDS();
4007#undef VISIT_MD_FIELDS
4008
Amjad Aboud7faeecc2016-12-25 10:12:09 +00004009 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4010 checksumkind.Val, checksum.Val));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004011 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004012}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00004013
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004014/// ParseDICompileUnit:
4015/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004016/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
Adrian Prantlb939a252016-03-31 23:56:58 +00004017/// splitDebugFilename: "abc.debug",
Adrian Prantl75819ae2016-04-15 15:57:41 +00004018/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
Amjad Abouda9bcf162015-12-10 12:56:35 +00004019/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004020bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004021 if (!IsDistinct)
4022 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4023
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004024#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4025 REQUIRED(language, DwarfLangField, ); \
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +00004026 REQUIRED(file, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004027 OPTIONAL(producer, MDStringField, ); \
4028 OPTIONAL(isOptimized, MDBoolField, ); \
4029 OPTIONAL(flags, MDStringField, ); \
4030 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4031 OPTIONAL(splitDebugFilename, MDStringField, ); \
Adrian Prantlb939a252016-03-31 23:56:58 +00004032 OPTIONAL(emissionKind, EmissionKindField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004033 OPTIONAL(enums, MDField, ); \
4034 OPTIONAL(retainedTypes, MDField, ); \
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004035 OPTIONAL(globals, MDField, ); \
Adrian Prantl1f599f92015-05-21 20:37:30 +00004036 OPTIONAL(imports, MDField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004037 OPTIONAL(macros, MDField, ); \
David Blaikiea01f2952016-08-24 18:29:49 +00004038 OPTIONAL(dwoId, MDUnsignedField, ); \
Dehao Chen0944a8c2017-02-01 22:45:09 +00004039 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4040 OPTIONAL(debugInfoForProfiling, MDBoolField, = false);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004041 PARSE_MD_FIELDS();
4042#undef VISIT_MD_FIELDS
4043
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00004044 Result = DICompileUnit::getDistinct(
4045 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4046 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
David Blaikiea01f2952016-08-24 18:29:49 +00004047 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
Dehao Chen0944a8c2017-02-01 22:45:09 +00004048 splitDebugInlining.Val, debugInfoForProfiling.Val);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004049 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004050}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00004051
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004052/// ParseDISubprogram:
4053/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004054/// file: !1, line: 7, type: !2, isLocal: false,
4055/// isDefinition: true, scopeLine: 8, containingType: !3,
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004056/// virtuality: DW_VIRTUALTIY_pure_virtual,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004057/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
Peter Collingbourned4bff302015-11-05 22:03:56 +00004058/// isOptimized: false, templateParams: !4, declaration: !5,
4059/// variables: !6)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004060bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004061 auto Loc = Lex.getLoc();
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004062#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4063 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004064 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004065 OPTIONAL(linkageName, MDStringField, ); \
4066 OPTIONAL(file, MDField, ); \
4067 OPTIONAL(line, LineField, ); \
4068 OPTIONAL(type, MDField, ); \
4069 OPTIONAL(isLocal, MDBoolField, ); \
4070 OPTIONAL(isDefinition, MDBoolField, (true)); \
4071 OPTIONAL(scopeLine, LineField, ); \
4072 OPTIONAL(containingType, MDField, ); \
Duncan P. N. Exon Smith890533e2015-02-13 01:28:16 +00004073 OPTIONAL(virtuality, DwarfVirtualityField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004074 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004075 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00004076 OPTIONAL(flags, DIFlagField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004077 OPTIONAL(isOptimized, MDBoolField, ); \
Adrian Prantl75819ae2016-04-15 15:57:41 +00004078 OPTIONAL(unit, MDField, ); \
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004079 OPTIONAL(templateParams, MDField, ); \
4080 OPTIONAL(declaration, MDField, ); \
4081 OPTIONAL(variables, MDField, );
4082 PARSE_MD_FIELDS();
4083#undef VISIT_MD_FIELDS
4084
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00004085 if (isDefinition.Val && !IsDistinct)
4086 return Lex.Error(
4087 Loc,
4088 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4089
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004090 Result = GET_OR_DISTINCT(
Adrian Prantl75819ae2016-04-15 15:57:41 +00004091 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4092 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4093 scopeLine.Val, containingType.Val, virtuality.Val,
Reid Klecknerb5af11d2016-07-01 02:41:21 +00004094 virtualIndex.Val, thisAdjustment.Val, flags.Val,
4095 isOptimized.Val, unit.Val, templateParams.Val,
4096 declaration.Val, variables.Val));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004097 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004098}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004099
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004100/// ParseDILexicalBlock:
4101/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4102bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004103#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004104 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004105 OPTIONAL(file, MDField, ); \
4106 OPTIONAL(line, LineField, ); \
4107 OPTIONAL(column, ColumnField, );
4108 PARSE_MD_FIELDS();
4109#undef VISIT_MD_FIELDS
4110
4111 Result = GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004112 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004113 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004114}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00004115
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004116/// ParseDILexicalBlockFile:
4117/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4118bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004119#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00004120 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004121 OPTIONAL(file, MDField, ); \
4122 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4123 PARSE_MD_FIELDS();
4124#undef VISIT_MD_FIELDS
4125
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004126 Result = GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004127 (Context, scope.Val, file.Val, discriminator.Val));
4128 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004129}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00004130
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004131/// ParseDINamespace:
4132/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4133bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004134#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4135 REQUIRED(scope, MDField, ); \
4136 OPTIONAL(file, MDField, ); \
4137 OPTIONAL(name, MDStringField, ); \
Adrian Prantldbfda632016-11-03 19:42:02 +00004138 OPTIONAL(line, LineField, ); \
4139 OPTIONAL(exportSymbols, MDBoolField, );
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004140 PARSE_MD_FIELDS();
4141#undef VISIT_MD_FIELDS
4142
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004143 Result = GET_OR_DISTINCT(DINamespace,
Adrian Prantldbfda632016-11-03 19:42:02 +00004144 (Context, scope.Val, file.Val, name.Val, line.Val, exportSymbols.Val));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004145 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004146}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00004147
Amjad Abouda9bcf162015-12-10 12:56:35 +00004148/// ParseDIMacro:
4149/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4150bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4151#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4152 REQUIRED(type, DwarfMacinfoTypeField, ); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004153 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004154 REQUIRED(name, MDStringField, ); \
4155 OPTIONAL(value, MDStringField, );
4156 PARSE_MD_FIELDS();
4157#undef VISIT_MD_FIELDS
4158
4159 Result = GET_OR_DISTINCT(DIMacro,
4160 (Context, type.Val, line.Val, name.Val, value.Val));
4161 return false;
4162}
4163
4164/// ParseDIMacroFile:
4165/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4166bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4167#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4168 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
Adrian Prantl58c19102016-12-22 00:29:00 +00004169 OPTIONAL(line, LineField, ); \
Amjad Abouda9bcf162015-12-10 12:56:35 +00004170 REQUIRED(file, MDField, ); \
4171 OPTIONAL(nodes, MDField, );
4172 PARSE_MD_FIELDS();
4173#undef VISIT_MD_FIELDS
4174
4175 Result = GET_OR_DISTINCT(DIMacroFile,
4176 (Context, type.Val, line.Val, file.Val, nodes.Val));
4177 return false;
4178}
4179
Adrian Prantlab1243f2015-06-29 23:03:47 +00004180/// ParseDIModule:
4181/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4182/// includePath: "/usr/include", isysroot: "/")
4183bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4184#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4185 REQUIRED(scope, MDField, ); \
4186 REQUIRED(name, MDStringField, ); \
4187 OPTIONAL(configMacros, MDStringField, ); \
4188 OPTIONAL(includePath, MDStringField, ); \
4189 OPTIONAL(isysroot, MDStringField, );
4190 PARSE_MD_FIELDS();
4191#undef VISIT_MD_FIELDS
4192
4193 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4194 configMacros.Val, includePath.Val, isysroot.Val));
4195 return false;
4196}
4197
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004198/// ParseDITemplateTypeParameter:
4199/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4200bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004201#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004202 OPTIONAL(name, MDStringField, ); \
4203 REQUIRED(type, MDField, );
4204 PARSE_MD_FIELDS();
4205#undef VISIT_MD_FIELDS
4206
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004207 Result =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004208 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004209 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004210}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004211
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004212/// ParseDITemplateValueParameter:
4213/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004214/// name: "V", type: !1, value: i32 7)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004215bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004216#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004217 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004218 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00004219 OPTIONAL(type, MDField, ); \
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004220 REQUIRED(value, MDField, );
4221 PARSE_MD_FIELDS();
4222#undef VISIT_MD_FIELDS
4223
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004224 Result = GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00004225 (Context, tag.Val, name.Val, type.Val, value.Val));
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004226 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004227}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00004228
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004229/// ParseDIGlobalVariable:
4230/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004231/// file: !1, line: 7, type: !2, isLocal: false,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004232/// isDefinition: true, declaration: !3, align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004233bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004234#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith94d58f82015-03-31 01:28:22 +00004235 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004236 OPTIONAL(scope, MDField, ); \
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004237 OPTIONAL(linkageName, MDStringField, ); \
4238 OPTIONAL(file, MDField, ); \
4239 OPTIONAL(line, LineField, ); \
4240 OPTIONAL(type, MDField, ); \
4241 OPTIONAL(isLocal, MDBoolField, ); \
4242 OPTIONAL(isDefinition, MDBoolField, (true)); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004243 OPTIONAL(declaration, MDField, ); \
4244 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004245 PARSE_MD_FIELDS();
4246#undef VISIT_MD_FIELDS
4247
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004248 Result = GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004249 (Context, scope.Val, name.Val, linkageName.Val,
4250 file.Val, line.Val, type.Val, isLocal.Val,
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004251 isDefinition.Val, declaration.Val, align.Val));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004252 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004253}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00004254
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004255/// ParseDILocalVariable:
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004256/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004257/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4258/// align: 8)
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004259/// ::= !DILocalVariable(scope: !0, name: "foo",
Victor Leschuk2ede1262016-10-20 00:13:12 +00004260/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4261/// align: 8)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004262bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004263#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smithe2c61d92015-03-27 17:56:39 +00004264 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004265 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004266 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004267 OPTIONAL(file, MDField, ); \
4268 OPTIONAL(line, LineField, ); \
4269 OPTIONAL(type, MDField, ); \
Victor Leschuk2ede1262016-10-20 00:13:12 +00004270 OPTIONAL(flags, DIFlagField, ); \
4271 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004272 PARSE_MD_FIELDS();
4273#undef VISIT_MD_FIELDS
4274
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004275 Result = GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00004276 (Context, scope.Val, name.Val, file.Val, line.Val,
Victor Leschuk2ede1262016-10-20 00:13:12 +00004277 type.Val, arg.Val, flags.Val, align.Val));
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004278 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004279}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00004280
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004281/// ParseDIExpression:
4282/// ::= !DIExpression(0, 7, -1)
4283bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004284 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4285 Lex.Lex();
4286
4287 if (ParseToken(lltok::lparen, "expected '(' here"))
4288 return true;
4289
4290 SmallVector<uint64_t, 8> Elements;
4291 if (Lex.getKind() != lltok::rparen)
4292 do {
4293 if (Lex.getKind() == lltok::DwarfOp) {
4294 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4295 Lex.Lex();
4296 Elements.push_back(Op);
4297 continue;
4298 }
4299 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4300 }
4301
4302 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4303 return TokError("expected unsigned integer");
4304
4305 auto &U = Lex.getAPSIntVal();
4306 if (U.ugt(UINT64_MAX))
4307 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4308 Elements.push_back(U.getZExtValue());
4309 Lex.Lex();
4310 } while (EatIfPresent(lltok::comma));
4311
4312 if (ParseToken(lltok::rparen, "expected ')' here"))
4313 return true;
4314
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004315 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004316 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004317}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00004318
Adrian Prantlbceaaa92016-12-20 02:09:43 +00004319/// ParseDIGlobalVariableExpression:
4320/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4321bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4322 bool IsDistinct) {
4323#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4324 REQUIRED(var, MDField, ); \
4325 OPTIONAL(expr, MDField, );
4326 PARSE_MD_FIELDS();
4327#undef VISIT_MD_FIELDS
4328
4329 Result =
4330 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4331 return false;
4332}
4333
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004334/// ParseDIObjCProperty:
4335/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004336/// getter: "getFoo", attributes: 7, type: !2)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004337bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004338#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
Duncan P. N. Exon Smith3eea1962015-03-16 19:01:54 +00004339 OPTIONAL(name, MDStringField, ); \
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004340 OPTIONAL(file, MDField, ); \
4341 OPTIONAL(line, LineField, ); \
4342 OPTIONAL(setter, MDStringField, ); \
4343 OPTIONAL(getter, MDStringField, ); \
4344 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4345 OPTIONAL(type, MDField, );
4346 PARSE_MD_FIELDS();
4347#undef VISIT_MD_FIELDS
4348
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004349 Result = GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004350 (Context, name.Val, file.Val, line.Val, setter.Val,
4351 getter.Val, attributes.Val, type.Val));
4352 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004353}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00004354
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004355/// ParseDIImportedEntity:
4356/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004357/// line: 7, name: "foo")
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004358bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004359#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4360 REQUIRED(tag, DwarfTagField, ); \
4361 REQUIRED(scope, MDField, ); \
4362 OPTIONAL(entity, MDField, ); \
4363 OPTIONAL(line, LineField, ); \
4364 OPTIONAL(name, MDStringField, );
4365 PARSE_MD_FIELDS();
4366#undef VISIT_MD_FIELDS
4367
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004368 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004369 entity.Val, line.Val, name.Val));
4370 return false;
Duncan P. N. Exon Smithed458fa2015-02-10 01:08:16 +00004371}
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00004372
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004373#undef PARSE_MD_FIELD
Duncan P. N. Exon Smith2a6b5fc2015-01-19 23:44:41 +00004374#undef NOP_FIELD
4375#undef REQUIRE_FIELD
4376#undef DECLARE_FIELD
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004377
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004378/// ParseMetadataAsValue
4379/// ::= metadata i32 %local
4380/// ::= metadata i32 @global
4381/// ::= metadata i32 7
4382/// ::= metadata !0
4383/// ::= metadata !{...}
4384/// ::= metadata !"string"
4385bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4386 // Note: the type 'metadata' has already been parsed.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004387 Metadata *MD;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004388 if (ParseMetadata(MD, &PFS))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004389 return true;
4390
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004391 V = MetadataAsValue::get(Context, MD);
4392 return false;
4393}
4394
4395/// ParseValueAsMetadata
4396/// ::= i32 %local
4397/// ::= i32 @global
4398/// ::= i32 7
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004399bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4400 PerFunctionState *PFS) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004401 Type *Ty;
4402 LocTy Loc;
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004403 if (ParseType(Ty, TypeMsg, Loc))
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004404 return true;
4405 if (Ty->isMetadataTy())
4406 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4407
4408 Value *V;
4409 if (ParseValue(Ty, V, PFS))
4410 return true;
4411
4412 MD = ValueAsMetadata::get(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004413 return false;
4414}
4415
4416/// ParseMetadata
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004417/// ::= i32 %local
4418/// ::= i32 @global
4419/// ::= i32 7
Dan Gohman8939ba332010-07-14 18:26:50 +00004420/// ::= !42
4421/// ::= !{...}
4422/// ::= !"string"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004423/// ::= !DILocation(...)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004424bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00004425 if (Lex.getKind() == lltok::MetadataVar) {
4426 MDNode *N;
4427 if (ParseSpecializedMDNode(N))
4428 return true;
4429 MD = N;
4430 return false;
4431 }
4432
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004433 // ValueAsMetadata:
4434 // <type> <value>
4435 if (Lex.getKind() != lltok::exclaim)
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00004436 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00004437
4438 // '!'.
4439 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4440 Lex.Lex();
Dan Gohman8939ba332010-07-14 18:26:50 +00004441
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004442 // MDString:
4443 // ::= '!' STRINGCONSTANT
4444 if (Lex.getKind() == lltok::StringConstant) {
4445 MDString *S;
4446 if (ParseMDString(S))
4447 return true;
4448 MD = S;
4449 return false;
4450 }
4451
Dan Gohman8939ba332010-07-14 18:26:50 +00004452 // MDNode:
4453 // !{ ... }
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004454 // !7
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004455 MDNode *N;
Duncan P. N. Exon Smithf825dae2015-01-12 22:26:48 +00004456 if (ParseMDNodeTail(N))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004457 return true;
Duncan P. N. Exon Smith62a79192015-01-12 22:24:50 +00004458 MD = N;
Dan Gohman8939ba332010-07-14 18:26:50 +00004459 return false;
4460}
4461
Victor Hernandez9d75c962010-01-11 22:31:58 +00004462//===----------------------------------------------------------------------===//
4463// Function Parsing.
4464//===----------------------------------------------------------------------===//
4465
Chris Lattner229907c2011-07-18 04:54:35 +00004466bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
David Majnemer8a1c45d2015-12-12 05:38:55 +00004467 PerFunctionState *PFS) {
Duncan Sands19d0b472010-02-16 11:11:14 +00004468 if (Ty->isFunctionTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004469 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004470
Chris Lattnerac161bf2009-01-02 07:01:27 +00004471 switch (ID.Kind) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004472 case ValID::t_LocalID:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004473 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004474 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004475 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004476 case ValID::t_LocalName:
Victor Hernandez9d75c962010-01-11 22:31:58 +00004477 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004478 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004479 return V == nullptr;
Victor Hernandez9d75c962010-01-11 22:31:58 +00004480 case ValID::t_InlineAsm: {
Karl Schimpf44876c52015-09-03 16:18:32 +00004481 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
Victor Hernandez9d75c962010-01-11 22:31:58 +00004482 return Error(ID.Loc, "invalid type for inline asm constraint string");
David Blaikie41ba2b42015-07-27 23:32:19 +00004483 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4484 (ID.UIntVal >> 1) & 1,
4485 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
Victor Hernandez9d75c962010-01-11 22:31:58 +00004486 return false;
4487 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004488 case ValID::t_GlobalName:
4489 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004490 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004491 case ValID::t_GlobalID:
4492 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004493 return V == nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004494 case ValID::t_APSInt:
Duncan Sands19d0b472010-02-16 11:11:14 +00004495 if (!Ty->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004496 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad583abbc2010-12-07 08:25:19 +00004497 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonedb4a702009-07-24 23:12:02 +00004498 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004499 return false;
4500 case ValID::t_APFloat:
Duncan Sands9dff9be2010-02-15 16:12:20 +00004501 if (!Ty->isFloatingPointTy() ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00004502 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4503 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004504
Dan Gohman518cda42011-12-17 00:04:22 +00004505 // The lexer has no type info, so builds all half, float, and double FP
4506 // constants as double. Fix this here. Long double does not need this.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004507 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004508 bool Ignored;
Dan Gohman518cda42011-12-17 00:04:22 +00004509 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004510 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004511 &Ignored);
4512 else if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004513 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Dan Gohman518cda42011-12-17 00:04:22 +00004514 &Ignored);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004515 }
Owen Anderson69c464d2009-07-27 20:59:43 +00004516 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004517
Chris Lattner8f57d29e2009-01-05 18:24:23 +00004518 if (V->getType() != Ty)
4519 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00004520 getTypeString(Ty) + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004521
Chris Lattnerac161bf2009-01-02 07:01:27 +00004522 return false;
4523 case ValID::t_Null:
Duncan Sands19d0b472010-02-16 11:11:14 +00004524 if (!Ty->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004525 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004526 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004527 return false;
4528 case ValID::t_Undef:
Chris Lattnerffa07782009-01-05 08:13:38 +00004529 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004530 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerffa07782009-01-05 08:13:38 +00004531 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004532 V = UndefValue::get(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004533 return false;
Chris Lattner998fa0a2009-01-05 07:52:51 +00004534 case ValID::t_EmptyArray:
Duncan Sands19d0b472010-02-16 11:11:14 +00004535 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner998fa0a2009-01-05 07:52:51 +00004536 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb292b8c2009-07-30 23:03:37 +00004537 V = UndefValue::get(Ty);
Chris Lattner998fa0a2009-01-05 07:52:51 +00004538 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004539 case ValID::t_Zero:
Chris Lattnerffa07782009-01-05 08:13:38 +00004540 // FIXME: LabelTy should not be a first-class type.
Chris Lattnerfdd87902009-10-05 05:54:46 +00004541 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00004542 return Error(ID.Loc, "invalid type for null constant");
Owen Anderson5a1acd92009-07-31 20:28:14 +00004543 V = Constant::getNullValue(Ty);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004544 return false;
David Majnemerf0f224d2015-11-11 21:57:16 +00004545 case ValID::t_None:
4546 if (!Ty->isTokenTy())
4547 return Error(ID.Loc, "invalid type for none constant");
4548 V = Constant::getNullValue(Ty);
4549 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004550 case ValID::t_Constant:
Chris Lattner13ee7952010-08-28 04:09:24 +00004551 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004552 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattner392be582010-02-12 20:49:41 +00004553
Chris Lattnerac161bf2009-01-02 07:01:27 +00004554 V = ID.ConstantVal;
4555 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004556 case ValID::t_ConstantStruct:
4557 case ValID::t_PackedConstantStruct:
Chris Lattner229907c2011-07-18 04:54:35 +00004558 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004559 if (ST->getNumElements() != ID.UIntVal)
4560 return Error(ID.Loc,
4561 "initializer with struct type has wrong # elements");
4562 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4563 return Error(ID.Loc, "packed'ness of initializer and type don't match");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004564
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004565 // Verify that the elements are compatible with the structtype.
4566 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4567 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4568 return Error(ID.Loc, "element " + Twine(i) +
4569 " of struct initializer doesn't match struct element type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004570
David Blaikieadbda4b2015-08-03 20:08:41 +00004571 V = ConstantStruct::get(
4572 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004573 } else
4574 return Error(ID.Loc, "constant expression type mismatch");
4575 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004576 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00004577 llvm_unreachable("Invalid ValID");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004578}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004579
Alex Lorenzd2255952015-07-17 22:07:03 +00004580bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4581 C = nullptr;
4582 ValID ID;
4583 auto Loc = Lex.getLoc();
4584 if (ParseValID(ID, /*PFS=*/nullptr))
4585 return true;
4586 switch (ID.Kind) {
4587 case ValID::t_APSInt:
4588 case ValID::t_APFloat:
Alex Lorenzb9a68db2015-09-09 13:44:33 +00004589 case ValID::t_Undef:
Alex Lorenzd2255952015-07-17 22:07:03 +00004590 case ValID::t_Constant:
4591 case ValID::t_ConstantStruct:
4592 case ValID::t_PackedConstantStruct: {
4593 Value *V;
4594 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4595 return true;
4596 assert(isa<Constant>(V) && "Expected a constant value");
4597 C = cast<Constant>(V);
4598 return false;
4599 }
4600 default:
4601 return Error(Loc, "expected a constant value");
4602 }
4603}
4604
David Majnemer8a1c45d2015-12-12 05:38:55 +00004605bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004606 V = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004607 ValID ID;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004608 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004609}
4610
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004611bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004612 Type *Ty = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004613 return ParseType(Ty) ||
4614 ParseValue(Ty, V, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004615}
4616
Chris Lattner3ed871f2009-10-27 19:13:16 +00004617bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4618 PerFunctionState &PFS) {
4619 Value *V;
4620 Loc = Lex.getLoc();
4621 if (ParseTypeAndValue(V, PFS)) return true;
4622 if (!isa<BasicBlock>(V))
4623 return Error(Loc, "expected a basic block");
4624 BB = cast<BasicBlock>(V);
4625 return false;
4626}
4627
Chris Lattnerac161bf2009-01-02 07:01:27 +00004628/// FunctionHeader
4629/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindola45e6c192011-01-08 16:42:36 +00004630/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
David Majnemer7fddecc2015-06-17 20:52:32 +00004631/// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
Chris Lattnerac161bf2009-01-02 07:01:27 +00004632bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4633 // Parse the linkage.
4634 LocTy LinkageLoc = Lex.getLoc();
4635 unsigned Linkage;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004636
Kostya Serebryanya5054ad2012-01-20 17:56:17 +00004637 unsigned Visibility;
Nico Rieck7157bb72014-01-14 15:22:47 +00004638 unsigned DLLStorageClass;
Bill Wendling50d27842012-10-15 20:35:56 +00004639 AttrBuilder RetAttrs;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00004640 unsigned CC;
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004641 bool HasLinkage;
Craig Topper2617dcc2014-04-15 06:32:26 +00004642 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004643 LocTy RetTypeLoc = Lex.getLoc();
Rafael Espindola2615c9e2016-05-12 12:37:52 +00004644 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4645 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00004646 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004647 return true;
4648
4649 // Verify that the linkage is ok.
4650 switch ((GlobalValue::LinkageTypes)Linkage) {
4651 case GlobalValue::ExternalLinkage:
4652 break; // always ok.
Duncan Sandse2881052009-03-11 08:08:06 +00004653 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004654 if (isDefine)
4655 return Error(LinkageLoc, "invalid linkage for function definition");
4656 break;
Rafael Espindola6de96a12009-01-15 20:18:42 +00004657 case GlobalValue::PrivateLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004658 case GlobalValue::InternalLinkage:
Nick Lewycky8019af62009-04-13 07:02:02 +00004659 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands12da8ce2009-03-07 15:45:40 +00004660 case GlobalValue::LinkOnceAnyLinkage:
4661 case GlobalValue::LinkOnceODRLinkage:
4662 case GlobalValue::WeakAnyLinkage:
4663 case GlobalValue::WeakODRLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004664 if (!isDefine)
4665 return Error(LinkageLoc, "invalid linkage for function declaration");
4666 break;
4667 case GlobalValue::AppendingLinkage:
Duncan Sands4581beb2009-03-11 20:14:15 +00004668 case GlobalValue::CommonLinkage:
Chris Lattnerac161bf2009-01-02 07:01:27 +00004669 return Error(LinkageLoc, "invalid function linkage type");
4670 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004671
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004672 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4673 return Error(LinkageLoc,
4674 "symbol with local linkage must have default visibility");
4675
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004676 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerac161bf2009-01-02 07:01:27 +00004677 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004678
Chris Lattnerac161bf2009-01-02 07:01:27 +00004679 LocTy NameLoc = Lex.getLoc();
Chris Lattner778c62c2009-02-18 21:48:13 +00004680
4681 std::string FunctionName;
4682 if (Lex.getKind() == lltok::GlobalVar) {
4683 FunctionName = Lex.getStrVal();
4684 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4685 unsigned NameID = Lex.getUIntVal();
4686
4687 if (NameID != NumberedVals.size())
4688 return TokError("function expected to be numbered '%" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004689 Twine(NumberedVals.size()) + "'");
Chris Lattner778c62c2009-02-18 21:48:13 +00004690 } else {
4691 return TokError("expected function name");
4692 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004693
Chris Lattner3822f632009-01-02 08:05:26 +00004694 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004695
Chris Lattner3822f632009-01-02 08:05:26 +00004696 if (Lex.getKind() != lltok::lparen)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004697 return TokError("expected '(' in function argument list");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004698
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004699 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004700 bool isVarArg;
Bill Wendling50d27842012-10-15 20:35:56 +00004701 AttrBuilder FuncAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00004702 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00004703 LocTy BuiltinLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004704 std::string Section;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004705 unsigned Alignment;
Chris Lattner3822f632009-01-02 08:05:26 +00004706 std::string GC;
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004707 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola563eb4b2011-01-25 19:09:56 +00004708 LocTy UnnamedAddrLoc;
Craig Topper2617dcc2014-04-15 06:32:26 +00004709 Constant *Prefix = nullptr;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004710 Constant *Prologue = nullptr;
David Majnemer7fddecc2015-06-17 20:52:32 +00004711 Constant *PersonalityFn = nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00004712 Comdat *C;
Chris Lattner3822f632009-01-02 08:05:26 +00004713
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004714 if (ParseArgumentList(ArgList, isVarArg) ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004715 ParseOptionalUnnamedAddr(UnnamedAddr) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00004716 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
Michael Gottesman41748d72013-06-27 00:25:01 +00004717 BuiltinLoc) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004718 (EatIfPresent(lltok::kw_section) &&
4719 ParseStringConstant(Section)) ||
Rafael Espindola83a362c2015-01-06 22:55:16 +00004720 parseOptionalComdat(FunctionName, C) ||
Chris Lattner3822f632009-01-02 08:05:26 +00004721 ParseOptionalAlignment(Alignment) ||
4722 (EatIfPresent(lltok::kw_gc) &&
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004723 ParseStringConstant(GC)) ||
4724 (EatIfPresent(lltok::kw_prefix) &&
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004725 ParseGlobalTypeAndValue(Prefix)) ||
4726 (EatIfPresent(lltok::kw_prologue) &&
David Majnemer7fddecc2015-06-17 20:52:32 +00004727 ParseGlobalTypeAndValue(Prologue)) ||
4728 (EatIfPresent(lltok::kw_personality) &&
4729 ParseGlobalTypeAndValue(PersonalityFn)))
Chris Lattner3822f632009-01-02 08:05:26 +00004730 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004731
Michael Gottesman41748d72013-06-27 00:25:01 +00004732 if (FuncAttrs.contains(Attribute::Builtin))
4733 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
Bill Wendling09bd1f72013-02-22 00:12:35 +00004734
Chris Lattnerac161bf2009-01-02 07:01:27 +00004735 // If the alignment was parsed as an attribute, move to the alignment field.
Bill Wendlingc6daefa2012-10-08 23:27:46 +00004736 if (FuncAttrs.hasAlignmentAttr()) {
Bill Wendling9be77592012-09-21 15:26:31 +00004737 Alignment = FuncAttrs.getAlignment();
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004738 FuncAttrs.removeAttribute(Attribute::Alignment);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004739 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004740
Chris Lattnerac161bf2009-01-02 07:01:27 +00004741 // Okay, if we got here, the function is syntactically valid. Convert types
4742 // and do semantic checks.
Jay Foadb804a2b2011-07-12 14:06:48 +00004743 std::vector<Type*> ParamTypeList;
Bill Wendlingf5075a42013-01-27 02:24:02 +00004744 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004745
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004746 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004747 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4748 AttributeSet::ReturnIndex,
4749 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004750
Chris Lattnerac161bf2009-01-02 07:01:27 +00004751 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004752 ParamTypeList.push_back(ArgList[i].Ty);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00004753 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4754 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00004755 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4756 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00004757 }
4758
Bill Wendling3bef2dd2012-09-19 23:54:18 +00004759 if (FuncAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00004760 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4761 AttributeSet::FunctionIndex,
4762 FuncAttrs));
Chris Lattnerac161bf2009-01-02 07:01:27 +00004763
Bill Wendlinge94d8432012-12-07 23:16:57 +00004764 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004765
Bill Wendling749a43d2012-12-30 13:50:49 +00004766 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004767 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4768
Chris Lattner229907c2011-07-18 04:54:35 +00004769 FunctionType *FT =
Owen Anderson4056ca92009-07-29 22:17:13 +00004770 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattner229907c2011-07-18 04:54:35 +00004771 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004772
Craig Topper2617dcc2014-04-15 06:32:26 +00004773 Fn = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00004774 if (!FunctionName.empty()) {
4775 // If this was a definition of a forward reference, remove the definition
4776 // from the forward reference table and fill in the forward ref.
David Blaikie9ebdc692015-09-21 21:07:50 +00004777 auto FRVI = ForwardRefVals.find(FunctionName);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004778 if (FRVI != ForwardRefVals.end()) {
4779 Fn = M->getFunction(FunctionName);
Nick Lewycky686d7cb2012-10-11 00:38:25 +00004780 if (!Fn)
4781 return Error(FRVI->second.second, "invalid forward reference to "
4782 "function as global value!");
Chris Lattnerc239eb72010-04-20 04:49:11 +00004783 if (Fn->getType() != PFT)
4784 return Error(FRVI->second.second, "invalid forward reference to "
4785 "function '" + FunctionName + "' with wrong type!");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004786
Chris Lattnerac161bf2009-01-02 07:01:27 +00004787 ForwardRefVals.erase(FRVI);
4788 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattner5756c162011-06-17 07:06:44 +00004789 // Reject redefinitions.
4790 return Error(NameLoc, "invalid redefinition of function '" +
4791 FunctionName + "'");
Chris Lattnere38317f2009-10-25 23:22:50 +00004792 } else if (M->getNamedValue(FunctionName)) {
4793 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004794 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004795
Dan Gohman399d6ae2009-08-29 23:37:49 +00004796 } else {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004797 // If this is a definition of a forward referenced function, make sure the
4798 // types agree.
David Blaikie9ebdc692015-09-21 21:07:50 +00004799 auto I = ForwardRefValIDs.find(NumberedVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00004800 if (I != ForwardRefValIDs.end()) {
4801 Fn = cast<Function>(I->second.first);
4802 if (Fn->getType() != PFT)
4803 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerc7583112010-09-27 17:42:11 +00004804 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004805 ForwardRefValIDs.erase(I);
4806 }
4807 }
4808
Craig Topper2617dcc2014-04-15 06:32:26 +00004809 if (!Fn)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004810 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4811 else // Move the forward-reference to the correct spot in the module.
4812 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4813
4814 if (FunctionName.empty())
4815 NumberedVals.push_back(Fn);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004816
Chris Lattnerac161bf2009-01-02 07:01:27 +00004817 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4818 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Nico Rieck7157bb72014-01-14 15:22:47 +00004819 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004820 Fn->setCallingConv(CC);
4821 Fn->setAttributes(PAL);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004822 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerac161bf2009-01-02 07:01:27 +00004823 Fn->setAlignment(Alignment);
4824 Fn->setSection(Section);
David Majnemerdad0a642014-06-27 18:19:56 +00004825 Fn->setComdat(C);
David Majnemer7fddecc2015-06-17 20:52:32 +00004826 Fn->setPersonalityFn(PersonalityFn);
Benjamin Kramer728f4442016-05-29 10:46:35 +00004827 if (!GC.empty()) Fn->setGC(GC);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004828 Fn->setPrefixData(Prefix);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004829 Fn->setPrologueData(Prologue);
Bill Wendlingb32b0412013-02-08 06:32:06 +00004830 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004831
Chris Lattnerac161bf2009-01-02 07:01:27 +00004832 // Add all of the arguments we parsed to the function.
4833 Function::arg_iterator ArgIt = Fn->arg_begin();
4834 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4835 // If the argument has a name, insert it into the argument symbol table.
4836 if (ArgList[i].Name.empty()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004837
Chris Lattnerac161bf2009-01-02 07:01:27 +00004838 // Set the name, if it conflicted, it will be auto-renamed.
4839 ArgIt->setName(ArgList[i].Name);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004840
Benjamin Kramer1dc34b42010-10-16 11:28:23 +00004841 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004842 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4843 ArgList[i].Name + "'");
4844 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004845
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004846 if (isDefine)
4847 return false;
4848
Robin Morisset039781e2014-08-29 21:53:01 +00004849 // Check the declaration has no block address forward references.
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004850 ValID ID;
4851 if (FunctionName.empty()) {
4852 ID.Kind = ValID::t_GlobalID;
4853 ID.UIntVal = NumberedVals.size() - 1;
4854 } else {
4855 ID.Kind = ValID::t_GlobalName;
4856 ID.StrVal = FunctionName;
4857 }
4858 auto Blocks = ForwardRefBlockAddresses.find(ID);
4859 if (Blocks != ForwardRefBlockAddresses.end())
4860 return Error(Blocks->first.Loc,
4861 "cannot take blockaddress inside a declaration");
Chris Lattnerac161bf2009-01-02 07:01:27 +00004862 return false;
4863}
4864
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004865bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4866 ValID ID;
4867 if (FunctionNumber == -1) {
4868 ID.Kind = ValID::t_GlobalName;
4869 ID.StrVal = F.getName();
4870 } else {
4871 ID.Kind = ValID::t_GlobalID;
4872 ID.UIntVal = FunctionNumber;
4873 }
4874
4875 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4876 if (Blocks == P.ForwardRefBlockAddresses.end())
4877 return false;
4878
4879 for (const auto &I : Blocks->second) {
4880 const ValID &BBID = I.first;
4881 GlobalValue *GV = I.second;
4882
4883 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4884 "Expected local id or name");
4885 BasicBlock *BB;
4886 if (BBID.Kind == ValID::t_LocalName)
4887 BB = GetBB(BBID.StrVal, BBID.Loc);
4888 else
4889 BB = GetBB(BBID.UIntVal, BBID.Loc);
4890 if (!BB)
4891 return P.Error(BBID.Loc, "referenced value is not a basic block");
4892
4893 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4894 GV->eraseFromParent();
4895 }
4896
4897 P.ForwardRefBlockAddresses.erase(Blocks);
4898 return false;
4899}
Chris Lattnerac161bf2009-01-02 07:01:27 +00004900
4901/// ParseFunctionBody
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004902/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
Chris Lattnerac161bf2009-01-02 07:01:27 +00004903bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner4649a732011-06-17 06:42:57 +00004904 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004905 return TokError("expected '{' in function body");
4906 Lex.Lex(); // eat the {.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004907
Chris Lattner3432c622009-10-28 03:39:23 +00004908 int FunctionNumber = -1;
4909 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004910
Chris Lattner3432c622009-10-28 03:39:23 +00004911 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004912
Duncan P. N. Exon Smith17169902014-08-19 00:13:19 +00004913 // Resolve block addresses and allow basic blocks to be forward-declared
4914 // within this function.
4915 if (PFS.resolveForwardRefBlockAddresses())
4916 return true;
4917 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4918
Chris Lattnerbbddd962010-01-09 19:20:07 +00004919 // We need at least one basic block.
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004920 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
Chris Lattnerbbddd962010-01-09 19:20:07 +00004921 return TokError("function body requires at least one basic block");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004922
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004923 while (Lex.getKind() != lltok::rbrace &&
4924 Lex.getKind() != lltok::kw_uselistorder)
Chris Lattnerac161bf2009-01-02 07:01:27 +00004925 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004926
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004927 while (Lex.getKind() != lltok::rbrace)
4928 if (ParseUseListOrder(&PFS))
4929 return true;
4930
Chris Lattnerac161bf2009-01-02 07:01:27 +00004931 // Eat the }.
4932 Lex.Lex();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004933
Chris Lattnerac161bf2009-01-02 07:01:27 +00004934 // Verify function is ok.
Chris Lattner3432c622009-10-28 03:39:23 +00004935 return PFS.FinishFunction();
Chris Lattnerac161bf2009-01-02 07:01:27 +00004936}
4937
4938/// ParseBasicBlock
4939/// ::= LabelStr? Instruction*
4940bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4941 // If this basic block starts out with a name, remember it.
4942 std::string Name;
4943 LocTy NameLoc = Lex.getLoc();
4944 if (Lex.getKind() == lltok::LabelStr) {
4945 Name = Lex.getStrVal();
4946 Lex.Lex();
4947 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004948
Chris Lattnerac161bf2009-01-02 07:01:27 +00004949 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
Owen Anderson576a9a22015-03-02 05:25:09 +00004950 if (!BB)
4951 return Error(NameLoc,
4952 "unable to create block named '" + Name + "'");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004953
Chris Lattnerac161bf2009-01-02 07:01:27 +00004954 std::string NameStr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004955
Chris Lattnerac161bf2009-01-02 07:01:27 +00004956 // Parse the instructions in this block until we get a terminator.
4957 Instruction *Inst;
4958 do {
4959 // This instruction may have three possibilities for a name: a) none
4960 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4961 LocTy NameLoc = Lex.getLoc();
4962 int NameID = -1;
4963 NameStr = "";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004964
Chris Lattnerac161bf2009-01-02 07:01:27 +00004965 if (Lex.getKind() == lltok::LocalVarID) {
4966 NameID = Lex.getUIntVal();
4967 Lex.Lex();
4968 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4969 return true;
Chris Lattnerdef19492011-06-17 06:36:20 +00004970 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00004971 NameStr = Lex.getStrVal();
4972 Lex.Lex();
4973 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4974 return true;
4975 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004976
Chris Lattner77b89dc2009-12-30 05:23:43 +00004977 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Toppera2886c22012-02-07 05:05:23 +00004978 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattner77b89dc2009-12-30 05:23:43 +00004979 case InstError: return true;
4980 case InstNormal:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004981 BB->getInstList().push_back(Inst);
4982
Chris Lattner77b89dc2009-12-30 05:23:43 +00004983 // With a normal result, we check to see if the instruction is followed by
4984 // a comma and metadata.
4985 if (EatIfPresent(lltok::comma))
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004986 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004987 return true;
4988 break;
4989 case InstExtraComma:
Chris Lattner2e664bd2010-04-07 04:08:57 +00004990 BB->getInstList().push_back(Inst);
4991
Chris Lattner77b89dc2009-12-30 05:23:43 +00004992 // If the instruction parser ate an extra comma at the end of it, it
4993 // *must* be followed by metadata.
Duncan P. N. Exon Smith27d702c2015-04-24 21:29:36 +00004994 if (ParseInstructionMetadata(*Inst))
Chris Lattner77b89dc2009-12-30 05:23:43 +00004995 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004996 break;
Chris Lattner77b89dc2009-12-30 05:23:43 +00004997 }
Devang Patelea8a4b92009-09-17 23:04:48 +00004998
Chris Lattnerac161bf2009-01-02 07:01:27 +00004999 // Set the name on the instruction.
5000 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5001 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005002
Chris Lattnerac161bf2009-01-02 07:01:27 +00005003 return false;
5004}
5005
5006//===----------------------------------------------------------------------===//
5007// Instruction Parsing.
5008//===----------------------------------------------------------------------===//
5009
5010/// ParseInstruction - Parse one of the many different instructions.
5011///
Chris Lattner77b89dc2009-12-30 05:23:43 +00005012int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5013 PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005014 lltok::Kind Token = Lex.getKind();
5015 if (Token == lltok::Eof)
5016 return TokError("found end of file when expecting more instructions");
5017 LocTy Loc = Lex.getLoc();
Chris Lattner89d856e2009-03-01 00:53:13 +00005018 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerac161bf2009-01-02 07:01:27 +00005019 Lex.Lex(); // Eat the keyword.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005020
Chris Lattnerac161bf2009-01-02 07:01:27 +00005021 switch (Token) {
5022 default: return Error(Loc, "expected instruction opcode");
5023 // Terminator Instructions.
Owen Anderson55f1c092009-08-13 21:58:54 +00005024 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005025 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5026 case lltok::kw_br: return ParseBr(Inst, PFS);
5027 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005028 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005029 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005030 case lltok::kw_resume: return ParseResume(Inst, PFS);
David Majnemer654e1302015-07-31 17:58:14 +00005031 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5032 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005033 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5034 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
David Majnemer8a1c45d2015-12-12 05:38:55 +00005035 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005036 // Binary Operators.
5037 case lltok::kw_add:
5038 case lltok::kw_sub:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005039 case lltok::kw_mul:
5040 case lltok::kw_shl: {
Chris Lattnera676c0f2011-02-07 16:40:21 +00005041 bool NUW = EatIfPresent(lltok::kw_nuw);
5042 bool NSW = EatIfPresent(lltok::kw_nsw);
5043 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005044
Chris Lattnera676c0f2011-02-07 16:40:21 +00005045 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005046
Chris Lattnera676c0f2011-02-07 16:40:21 +00005047 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5048 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5049 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005050 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005051 case lltok::kw_fadd:
5052 case lltok::kw_fsub:
Michael Ilseman92053172012-11-27 00:42:44 +00005053 case lltok::kw_fmul:
5054 case lltok::kw_fdiv:
5055 case lltok::kw_frem: {
5056 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5057 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5058 if (Res != 0)
5059 return Res;
5060 if (FMF.any())
5061 Inst->setFastMathFlags(FMF);
5062 return 0;
5063 }
Dan Gohmana5b96452009-06-04 22:49:04 +00005064
Chris Lattner35315d02011-02-06 21:44:57 +00005065 case lltok::kw_sdiv:
Chris Lattnera676c0f2011-02-07 16:40:21 +00005066 case lltok::kw_udiv:
5067 case lltok::kw_lshr:
5068 case lltok::kw_ashr: {
5069 bool Exact = EatIfPresent(lltok::kw_exact);
5070
5071 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5072 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5073 return false;
Dan Gohman9c7f8082009-07-27 16:11:46 +00005074 }
5075
Chris Lattnerac161bf2009-01-02 07:01:27 +00005076 case lltok::kw_urem:
Chris Lattner89d856e2009-03-01 00:53:13 +00005077 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005078 case lltok::kw_and:
5079 case lltok::kw_or:
Chris Lattner89d856e2009-03-01 00:53:13 +00005080 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
James Molloy88eb5352015-07-10 12:52:00 +00005081 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5082 case lltok::kw_fcmp: {
5083 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5084 int Res = ParseCompare(Inst, PFS, KeywordVal);
5085 if (Res != 0)
5086 return Res;
5087 if (FMF.any())
5088 Inst->setFastMathFlags(FMF);
5089 return 0;
5090 }
5091
Chris Lattnerac161bf2009-01-02 07:01:27 +00005092 // Casts.
5093 case lltok::kw_trunc:
5094 case lltok::kw_zext:
5095 case lltok::kw_sext:
5096 case lltok::kw_fptrunc:
5097 case lltok::kw_fpext:
5098 case lltok::kw_bitcast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00005099 case lltok::kw_addrspacecast:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005100 case lltok::kw_uitofp:
5101 case lltok::kw_sitofp:
5102 case lltok::kw_fptoui:
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005103 case lltok::kw_fptosi:
Chris Lattnerac161bf2009-01-02 07:01:27 +00005104 case lltok::kw_inttoptr:
Chris Lattner89d856e2009-03-01 00:53:13 +00005105 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005106 // Other.
5107 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattnerb55ab542009-01-05 08:18:44 +00005108 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005109 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5110 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5111 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5112 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlingfae14752011-08-12 20:24:12 +00005113 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Reid Kleckner5772b772014-04-24 20:14:34 +00005114 // Call.
5115 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5116 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5117 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005118 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005119 // Memory.
Victor Hernandezc7d6a832009-10-17 00:00:19 +00005120 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerbc639292011-11-27 06:56:53 +00005121 case lltok::kw_load: return ParseLoad(Inst, PFS);
5122 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedman02e737b2011-08-12 22:50:01 +00005123 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5124 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005125 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005126 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5127 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5128 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5129 }
5130}
5131
5132/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5133bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005134 if (Opc == Instruction::FCmp) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005135 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005136 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005137 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5138 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5139 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5140 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5141 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5142 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5143 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5144 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5145 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5146 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5147 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5148 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5149 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5150 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5151 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5152 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5153 }
5154 } else {
5155 switch (Lex.getKind()) {
David Tweeda11edf02013-01-07 13:32:38 +00005156 default: return TokError("expected icmp predicate (e.g. 'eq')");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005157 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5158 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5159 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5160 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5161 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5162 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5163 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5164 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5165 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5166 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5167 }
5168 }
5169 Lex.Lex();
5170 return false;
5171}
5172
5173//===----------------------------------------------------------------------===//
5174// Terminator Instructions.
5175//===----------------------------------------------------------------------===//
5176
5177/// ParseRet - Parse a return instruction.
Chris Lattner596760d2009-12-29 21:25:40 +00005178/// ::= 'ret' void (',' !dbg, !1)*
5179/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner33de4272011-06-17 06:49:41 +00005180bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005181 PerFunctionState &PFS) {
5182 SMLoc TypeLoc = Lex.getLoc();
Craig Topper2617dcc2014-04-15 06:32:26 +00005183 Type *Ty = nullptr;
Chris Lattnerf880ca22009-03-09 04:49:14 +00005184 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005185
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005186 Type *ResType = PFS.getFunction().getReturnType();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005187
Chris Lattnerfdd87902009-10-05 05:54:46 +00005188 if (Ty->isVoidTy()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005189 if (!ResType->isVoidTy())
5190 return Error(TypeLoc, "value doesn't match function result type '" +
5191 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005192
Owen Anderson55f1c092009-08-13 21:58:54 +00005193 Inst = ReturnInst::Create(Context);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005194 return false;
5195 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005196
Chris Lattnerac161bf2009-01-02 07:01:27 +00005197 Value *RV;
5198 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005199
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005200 if (ResType != RV->getType())
5201 return Error(TypeLoc, "value doesn't match function result type '" +
5202 getTypeString(ResType) + "'");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005203
Owen Anderson55f1c092009-08-13 21:58:54 +00005204 Inst = ReturnInst::Create(Context, RV);
Chris Lattner33de4272011-06-17 06:49:41 +00005205 return false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005206}
5207
Chris Lattnerac161bf2009-01-02 07:01:27 +00005208/// ParseBr
5209/// ::= 'br' TypeAndValue
5210/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5211bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5212 LocTy Loc, Loc2;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005213 Value *Op0;
5214 BasicBlock *Op1, *Op2;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005215 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005216
Chris Lattnerac161bf2009-01-02 07:01:27 +00005217 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5218 Inst = BranchInst::Create(BB);
5219 return false;
5220 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005221
Owen Anderson55f1c092009-08-13 21:58:54 +00005222 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005223 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005224
Chris Lattnerac161bf2009-01-02 07:01:27 +00005225 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005226 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005227 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005228 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005229 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005230
Chris Lattner3ed871f2009-10-27 19:13:16 +00005231 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005232 return false;
5233}
5234
5235/// ParseSwitch
5236/// Instruction
5237/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5238/// JumpTable
5239/// ::= (TypeAndValue ',' TypeAndValue)*
5240bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5241 LocTy CondLoc, BBLoc;
Chris Lattner3ed871f2009-10-27 19:13:16 +00005242 Value *Cond;
5243 BasicBlock *DefaultBB;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005244 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5245 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005246 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005247 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5248 return true;
5249
Duncan Sands19d0b472010-02-16 11:11:14 +00005250 if (!Cond->getType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005251 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005252
Chris Lattnerac161bf2009-01-02 07:01:27 +00005253 // Parse the jump table pairs.
5254 SmallPtrSet<Value*, 32> SeenCases;
5255 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5256 while (Lex.getKind() != lltok::rsquare) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005257 Value *Constant;
5258 BasicBlock *DestBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005259
Chris Lattnerac161bf2009-01-02 07:01:27 +00005260 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5261 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005262 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005263 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005264
David Blaikie70573dc2014-11-19 07:49:26 +00005265 if (!SeenCases.insert(Constant).second)
Chris Lattnerac161bf2009-01-02 07:01:27 +00005266 return Error(CondLoc, "duplicate case value in switch");
5267 if (!isa<ConstantInt>(Constant))
5268 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005269
Chris Lattner3ed871f2009-10-27 19:13:16 +00005270 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerac161bf2009-01-02 07:01:27 +00005271 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005272
Chris Lattnerac161bf2009-01-02 07:01:27 +00005273 Lex.Lex(); // Eat the ']'.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005274
Chris Lattner3ed871f2009-10-27 19:13:16 +00005275 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005276 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5277 SI->addCase(Table[i].first, Table[i].second);
5278 Inst = SI;
5279 return false;
5280}
5281
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005282/// ParseIndirectBr
Chris Lattner3ed871f2009-10-27 19:13:16 +00005283/// Instruction
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005284/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5285bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner3ed871f2009-10-27 19:13:16 +00005286 LocTy AddrLoc;
5287 Value *Address;
5288 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005289 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5290 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattner3ed871f2009-10-27 19:13:16 +00005291 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005292
Duncan Sands19d0b472010-02-16 11:11:14 +00005293 if (!Address->getType()->isPointerTy())
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005294 return Error(AddrLoc, "indirectbr address must have pointer type");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005295
Chris Lattner3ed871f2009-10-27 19:13:16 +00005296 // Parse the destination list.
5297 SmallVector<BasicBlock*, 16> DestList;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005298
Chris Lattner3ed871f2009-10-27 19:13:16 +00005299 if (Lex.getKind() != lltok::rsquare) {
5300 BasicBlock *DestBB;
5301 if (ParseTypeAndBasicBlock(DestBB, PFS))
5302 return true;
5303 DestList.push_back(DestBB);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005304
Chris Lattner3ed871f2009-10-27 19:13:16 +00005305 while (EatIfPresent(lltok::comma)) {
5306 if (ParseTypeAndBasicBlock(DestBB, PFS))
5307 return true;
5308 DestList.push_back(DestBB);
5309 }
5310 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005311
Chris Lattner3ed871f2009-10-27 19:13:16 +00005312 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5313 return true;
5314
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005315 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattner3ed871f2009-10-27 19:13:16 +00005316 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5317 IBI->addDestination(DestList[i]);
5318 Inst = IBI;
5319 return false;
5320}
5321
Chris Lattnerac161bf2009-01-02 07:01:27 +00005322/// ParseInvoke
5323/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5324/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5325bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5326 LocTy CallLoc = Lex.getLoc();
Bill Wendling50d27842012-10-15 20:35:56 +00005327 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005328 std::vector<unsigned> FwdRefAttrGrps;
Bill Wendling09bd1f72013-02-22 00:12:35 +00005329 LocTy NoBuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005330 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005331 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005332 LocTy RetTypeLoc;
5333 ValID CalleeID;
5334 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005335 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005336
Chris Lattner3ed871f2009-10-27 19:13:16 +00005337 BasicBlock *NormalBB, *UnwindBB;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005338 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005339 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005340 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
Bill Wendling09bd1f72013-02-22 00:12:35 +00005341 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5342 NoBuiltinLoc) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005343 ParseOptionalOperandBundles(BundleList, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005344 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005345 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005346 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattner3ed871f2009-10-27 19:13:16 +00005347 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005348 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005349
Chris Lattnerac161bf2009-01-02 07:01:27 +00005350 // If RetType is a non-function pointer type, then this is the short syntax
5351 // for the call, which means that RetType is just the return type. Infer the
5352 // rest of the function argument types from the arguments that are present.
David Blaikie445e3fb2015-04-24 19:32:54 +00005353 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5354 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005355 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005356 std::vector<Type*> ParamTypes;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005357 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5358 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005359
Chris Lattnerac161bf2009-01-02 07:01:27 +00005360 if (!FunctionType::isValidReturnType(RetType))
5361 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005362
Owen Anderson4056ca92009-07-29 22:17:13 +00005363 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005364 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005365
David Blaikie41ba2b42015-07-27 23:32:19 +00005366 CalleeID.FTy = Ty;
5367
Chris Lattnerac161bf2009-01-02 07:01:27 +00005368 // Look up the callee.
5369 Value *Callee;
David Blaikie445e3fb2015-04-24 19:32:54 +00005370 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5371 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005372
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005373 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005374 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005375 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005376 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5377 AttributeSet::ReturnIndex,
5378 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005379
Chris Lattnerac161bf2009-01-02 07:01:27 +00005380 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005381
Chris Lattnerac161bf2009-01-02 07:01:27 +00005382 // Loop through FunctionType's arguments and ensure they are specified
5383 // correctly. Also, gather any parameter attributes.
5384 FunctionType::param_iterator I = Ty->param_begin();
5385 FunctionType::param_iterator E = Ty->param_end();
5386 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005387 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005388 if (I != E) {
5389 ExpectedTy = *I++;
5390 } else if (!Ty->isVarArg()) {
5391 return Error(ArgList[i].Loc, "too many arguments specified");
5392 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005393
Chris Lattnerac161bf2009-01-02 07:01:27 +00005394 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5395 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005396 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005397 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00005398 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5399 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00005400 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5401 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005402 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005403
Chris Lattnerac161bf2009-01-02 07:01:27 +00005404 if (I != E)
5405 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005406
David Majnemer8d22abd2015-02-23 00:01:32 +00005407 if (FnAttrs.hasAttributes()) {
5408 if (FnAttrs.hasAlignmentAttr())
5409 return Error(CallLoc, "invoke instructions may not have an alignment");
5410
Bill Wendlingf5075a42013-01-27 02:24:02 +00005411 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5412 AttributeSet::FunctionIndex,
5413 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00005414 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005415
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005416 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00005417 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005418
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005419 InvokeInst *II =
5420 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005421 II->setCallingConv(CC);
5422 II->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00005423 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005424 Inst = II;
5425 return false;
5426}
5427
Bill Wendlingf891bf82011-07-31 06:30:59 +00005428/// ParseResume
5429/// ::= 'resume' TypeAndValue
5430bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5431 Value *Exn; LocTy ExnLoc;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005432 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5433 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005434
Bill Wendlingf891bf82011-07-31 06:30:59 +00005435 ResumeInst *RI = ResumeInst::Create(Exn);
5436 Inst = RI;
5437 return false;
5438}
Chris Lattnerac161bf2009-01-02 07:01:27 +00005439
David Majnemer654e1302015-07-31 17:58:14 +00005440bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5441 PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005442 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
David Majnemer654e1302015-07-31 17:58:14 +00005443 return true;
5444
5445 while (Lex.getKind() != lltok::rsquare) {
5446 // If this isn't the first argument, we need a comma.
5447 if (!Args.empty() &&
5448 ParseToken(lltok::comma, "expected ',' in argument list"))
5449 return true;
5450
5451 // Parse the argument.
5452 LocTy ArgLoc;
5453 Type *ArgTy = nullptr;
5454 if (ParseType(ArgTy, ArgLoc))
5455 return true;
5456
5457 Value *V;
5458 if (ArgTy->isMetadataTy()) {
5459 if (ParseMetadataAsValue(V, PFS))
5460 return true;
5461 } else {
5462 if (ParseValue(ArgTy, V, PFS))
5463 return true;
5464 }
5465 Args.push_back(V);
5466 }
5467
5468 Lex.Lex(); // Lex the ']'.
5469 return false;
5470}
5471
5472/// ParseCleanupRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005473/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
David Majnemer654e1302015-07-31 17:58:14 +00005474bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005475 Value *CleanupPad = nullptr;
David Majnemer654e1302015-07-31 17:58:14 +00005476
David Majnemer8a1c45d2015-12-12 05:38:55 +00005477 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5478 return true;
5479
5480 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005481 return true;
David Majnemer654e1302015-07-31 17:58:14 +00005482
5483 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5484 return true;
5485
5486 BasicBlock *UnwindBB = nullptr;
5487 if (Lex.getKind() == lltok::kw_to) {
5488 Lex.Lex();
5489 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5490 return true;
5491 } else {
5492 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5493 return true;
5494 }
5495 }
5496
David Majnemer8a1c45d2015-12-12 05:38:55 +00005497 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
David Majnemer654e1302015-07-31 17:58:14 +00005498 return false;
5499}
5500
5501/// ParseCatchRet
David Majnemer8a1c45d2015-12-12 05:38:55 +00005502/// ::= 'catchret' from Parent Value 'to' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005503bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005504 Value *CatchPad = nullptr;
David Majnemer0bc0eef2015-08-15 02:46:08 +00005505
David Majnemer8a1c45d2015-12-12 05:38:55 +00005506 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5507 return true;
5508
5509 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
David Majnemer0bc0eef2015-08-15 02:46:08 +00005510 return true;
5511
David Majnemer0bc0eef2015-08-15 02:46:08 +00005512 BasicBlock *BB;
5513 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5514 ParseTypeAndBasicBlock(BB, PFS))
5515 return true;
5516
David Majnemer8a1c45d2015-12-12 05:38:55 +00005517 Inst = CatchReturnInst::Create(CatchPad, BB);
5518 return false;
5519}
5520
5521/// ParseCatchSwitch
5522/// ::= 'catchswitch' within Parent
5523bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5524 Value *ParentPad;
5525 LocTy BBLoc;
5526
5527 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5528 return true;
5529
5530 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5531 Lex.getKind() != lltok::LocalVarID)
5532 return TokError("expected scope value for catchswitch");
5533
5534 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5535 return true;
5536
5537 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5538 return true;
5539
5540 SmallVector<BasicBlock *, 32> Table;
5541 do {
5542 BasicBlock *DestBB;
5543 if (ParseTypeAndBasicBlock(DestBB, PFS))
5544 return true;
5545 Table.push_back(DestBB);
5546 } while (EatIfPresent(lltok::comma));
5547
5548 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5549 return true;
5550
5551 if (ParseToken(lltok::kw_unwind,
5552 "expected 'unwind' after catchswitch scope"))
5553 return true;
5554
5555 BasicBlock *UnwindBB = nullptr;
5556 if (EatIfPresent(lltok::kw_to)) {
5557 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5558 return true;
5559 } else {
5560 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5561 return true;
5562 }
5563
5564 auto *CatchSwitch =
5565 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5566 for (BasicBlock *DestBB : Table)
5567 CatchSwitch->addHandler(DestBB);
5568 Inst = CatchSwitch;
David Majnemer654e1302015-07-31 17:58:14 +00005569 return false;
5570}
5571
5572/// ParseCatchPad
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005573/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
David Majnemer654e1302015-07-31 17:58:14 +00005574bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005575 Value *CatchSwitch = nullptr;
5576
5577 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5578 return true;
5579
5580 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5581 return TokError("expected scope value for catchpad");
5582
5583 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5584 return true;
5585
David Majnemer654e1302015-07-31 17:58:14 +00005586 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005587 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005588 return true;
5589
David Majnemer8a1c45d2015-12-12 05:38:55 +00005590 Inst = CatchPadInst::Create(CatchSwitch, Args);
David Majnemer654e1302015-07-31 17:58:14 +00005591 return false;
5592}
5593
David Majnemer654e1302015-07-31 17:58:14 +00005594/// ParseCleanupPad
David Majnemer8a1c45d2015-12-12 05:38:55 +00005595/// ::= 'cleanuppad' within Parent ParamList
David Majnemer654e1302015-07-31 17:58:14 +00005596bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00005597 Value *ParentPad = nullptr;
5598
5599 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5600 return true;
5601
5602 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5603 Lex.getKind() != lltok::LocalVarID)
5604 return TokError("expected scope value for cleanuppad");
5605
5606 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5607 return true;
5608
David Majnemer654e1302015-07-31 17:58:14 +00005609 SmallVector<Value *, 8> Args;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005610 if (ParseExceptionArgs(Args, PFS))
David Majnemer654e1302015-07-31 17:58:14 +00005611 return true;
5612
David Majnemer8a1c45d2015-12-12 05:38:55 +00005613 Inst = CleanupPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005614 return false;
5615}
5616
Chris Lattnerac161bf2009-01-02 07:01:27 +00005617//===----------------------------------------------------------------------===//
5618// Binary Operators.
5619//===----------------------------------------------------------------------===//
5620
5621/// ParseArithmetic
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005622/// ::= ArithmeticOps TypeAndValue ',' Value
5623///
5624/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5625/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerac161bf2009-01-02 07:01:27 +00005626bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005627 unsigned Opc, unsigned OperandType) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005628 LocTy Loc; Value *LHS, *RHS;
5629 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5630 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5631 ParseValue(LHS->getType(), RHS, PFS))
5632 return true;
5633
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005634 bool Valid;
5635 switch (OperandType) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00005636 default: llvm_unreachable("Unknown operand type!");
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005637 case 0: // int or FP.
Duncan Sands9dff9be2010-02-15 16:12:20 +00005638 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5639 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005640 break;
Duncan Sands9dff9be2010-02-15 16:12:20 +00005641 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5642 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005643 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005644
Chris Lattnereeefa9a2009-01-05 08:24:46 +00005645 if (!Valid)
5646 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005647
Chris Lattnerac161bf2009-01-02 07:01:27 +00005648 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5649 return false;
5650}
5651
5652/// ParseLogical
5653/// ::= ArithmeticOps TypeAndValue ',' Value {
5654bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5655 unsigned Opc) {
5656 LocTy Loc; Value *LHS, *RHS;
5657 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5658 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5659 ParseValue(LHS->getType(), RHS, PFS))
5660 return true;
5661
Duncan Sands9dff9be2010-02-15 16:12:20 +00005662 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005663 return Error(Loc,"instruction requires integer or integer vector operands");
5664
5665 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5666 return false;
5667}
5668
Chris Lattnerac161bf2009-01-02 07:01:27 +00005669/// ParseCompare
5670/// ::= 'icmp' IPredicates TypeAndValue ',' Value
5671/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerac161bf2009-01-02 07:01:27 +00005672bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5673 unsigned Opc) {
5674 // Parse the integer/fp comparison predicate.
5675 LocTy Loc;
5676 unsigned Pred;
5677 Value *LHS, *RHS;
5678 if (ParseCmpPredicate(Pred, Opc) ||
5679 ParseTypeAndValue(LHS, Loc, PFS) ||
5680 ParseToken(lltok::comma, "expected ',' after compare value") ||
5681 ParseValue(LHS->getType(), RHS, PFS))
5682 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005683
Chris Lattnerac161bf2009-01-02 07:01:27 +00005684 if (Opc == Instruction::FCmp) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00005685 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005686 return Error(Loc, "fcmp requires floating point operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005687 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005688 } else {
5689 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00005690 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00005691 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00005692 return Error(Loc, "icmp requires integer operands");
Dan Gohmanad1f0a12009-08-25 23:17:54 +00005693 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005694 }
5695 return false;
5696}
5697
5698//===----------------------------------------------------------------------===//
5699// Other Instructions.
5700//===----------------------------------------------------------------------===//
5701
5702
5703/// ParseCast
5704/// ::= CastOpc TypeAndValue 'to' Type
5705bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5706 unsigned Opc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005707 LocTy Loc;
5708 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005709 Type *DestTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005710 if (ParseTypeAndValue(Op, Loc, PFS) ||
5711 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5712 ParseType(DestTy))
5713 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005714
Chris Lattner89d856e2009-03-01 00:53:13 +00005715 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5716 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005717 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00005718 getTypeString(Op->getType()) + "' to '" +
5719 getTypeString(DestTy) + "'");
Chris Lattner89d856e2009-03-01 00:53:13 +00005720 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00005721 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5722 return false;
5723}
5724
5725/// ParseSelect
5726/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5727bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5728 LocTy Loc;
5729 Value *Op0, *Op1, *Op2;
5730 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5731 ParseToken(lltok::comma, "expected ',' after select condition") ||
5732 ParseTypeAndValue(Op1, PFS) ||
5733 ParseToken(lltok::comma, "expected ',' after select value") ||
5734 ParseTypeAndValue(Op2, PFS))
5735 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005736
Chris Lattnerac161bf2009-01-02 07:01:27 +00005737 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5738 return Error(Loc, Reason);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005739
Chris Lattnerac161bf2009-01-02 07:01:27 +00005740 Inst = SelectInst::Create(Op0, Op1, Op2);
5741 return false;
5742}
5743
Chris Lattnerb55ab542009-01-05 08:18:44 +00005744/// ParseVA_Arg
5745/// ::= 'va_arg' TypeAndValue ',' Type
5746bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005747 Value *Op;
Craig Topper2617dcc2014-04-15 06:32:26 +00005748 Type *EltTy = nullptr;
Chris Lattnerb55ab542009-01-05 08:18:44 +00005749 LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005750 if (ParseTypeAndValue(Op, PFS) ||
5751 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattnerb55ab542009-01-05 08:18:44 +00005752 ParseType(EltTy, TypeLoc))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005753 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005754
Chris Lattnerb55ab542009-01-05 08:18:44 +00005755 if (!EltTy->isFirstClassType())
5756 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00005757
5758 Inst = new VAArgInst(Op, EltTy);
5759 return false;
5760}
5761
5762/// ParseExtractElement
5763/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5764bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5765 LocTy Loc;
5766 Value *Op0, *Op1;
5767 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5768 ParseToken(lltok::comma, "expected ',' after extract value") ||
5769 ParseTypeAndValue(Op1, PFS))
5770 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005771
Chris Lattnerac161bf2009-01-02 07:01:27 +00005772 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5773 return Error(Loc, "invalid extractelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005774
Eric Christopherc9742252009-07-25 02:28:41 +00005775 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005776 return false;
5777}
5778
5779/// ParseInsertElement
5780/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5781bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5782 LocTy Loc;
5783 Value *Op0, *Op1, *Op2;
5784 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5785 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5786 ParseTypeAndValue(Op1, PFS) ||
5787 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5788 ParseTypeAndValue(Op2, PFS))
5789 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005790
Chris Lattnerac161bf2009-01-02 07:01:27 +00005791 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopherfef8db62009-07-23 01:01:32 +00005792 return Error(Loc, "invalid insertelement operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005793
Chris Lattnerac161bf2009-01-02 07:01:27 +00005794 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5795 return false;
5796}
5797
5798/// ParseShuffleVector
5799/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5800bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5801 LocTy Loc;
5802 Value *Op0, *Op1, *Op2;
5803 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5804 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5805 ParseTypeAndValue(Op1, PFS) ||
5806 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5807 ParseTypeAndValue(Op2, PFS))
5808 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005809
Chris Lattnerac161bf2009-01-02 07:01:27 +00005810 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperc1a6f982012-02-01 23:43:12 +00005811 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005812
Chris Lattnerac161bf2009-01-02 07:01:27 +00005813 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5814 return false;
5815}
5816
5817/// ParsePHI
Chris Lattnerc05471e2009-10-18 05:27:44 +00005818/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerf4f03422009-12-30 05:27:33 +00005819int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005820 Type *Ty = nullptr; LocTy TypeLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005821 Value *Op0, *Op1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005822
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005823 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005824 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5825 ParseValue(Ty, Op0, PFS) ||
5826 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005827 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005828 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5829 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005830
Chris Lattnerf4f03422009-12-30 05:27:33 +00005831 bool AteExtraComma = false;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005832 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005833
5834 while (true) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005835 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005836
Chris Lattner3822f632009-01-02 08:05:26 +00005837 if (!EatIfPresent(lltok::comma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005838 break;
5839
Chris Lattnerf4f03422009-12-30 05:27:33 +00005840 if (Lex.getKind() == lltok::MetadataVar) {
5841 AteExtraComma = true;
Devang Patel8f842d32009-10-16 18:45:49 +00005842 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005843 }
Devang Patel8f842d32009-10-16 18:45:49 +00005844
Chris Lattner3822f632009-01-02 08:05:26 +00005845 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005846 ParseValue(Ty, Op0, PFS) ||
5847 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson55f1c092009-08-13 21:58:54 +00005848 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005849 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5850 return true;
5851 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005852
Chris Lattnerac161bf2009-01-02 07:01:27 +00005853 if (!Ty->isFirstClassType())
5854 return Error(TypeLoc, "phi node must have first class type");
5855
Jay Foad52131342011-03-30 11:28:46 +00005856 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerac161bf2009-01-02 07:01:27 +00005857 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5858 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5859 Inst = PN;
Chris Lattnerf4f03422009-12-30 05:27:33 +00005860 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005861}
5862
Bill Wendlingfae14752011-08-12 20:24:12 +00005863/// ParseLandingPad
5864/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5865/// Clause
5866/// ::= 'catch' TypeAndValue
5867/// ::= 'filter'
5868/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5869bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005870 Type *Ty = nullptr; LocTy TyLoc;
Bill Wendlingfae14752011-08-12 20:24:12 +00005871
David Majnemer7fddecc2015-06-17 20:52:32 +00005872 if (ParseType(Ty, TyLoc))
Bill Wendlingfae14752011-08-12 20:24:12 +00005873 return true;
5874
David Majnemer7fddecc2015-06-17 20:52:32 +00005875 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
Bill Wendlingfae14752011-08-12 20:24:12 +00005876 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5877
5878 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5879 LandingPadInst::ClauseType CT;
5880 if (EatIfPresent(lltok::kw_catch))
5881 CT = LandingPadInst::Catch;
5882 else if (EatIfPresent(lltok::kw_filter))
5883 CT = LandingPadInst::Filter;
5884 else
5885 return TokError("expected 'catch' or 'filter' clause type");
5886
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005887 Value *V;
5888 LocTy VLoc;
Owen Andersonf8f259d2015-03-09 07:13:42 +00005889 if (ParseTypeAndValue(V, VLoc, PFS))
Bill Wendlingfae14752011-08-12 20:24:12 +00005890 return true;
Bill Wendlingfae14752011-08-12 20:24:12 +00005891
Bill Wendlinga52aa3c2011-08-12 20:52:25 +00005892 // A 'catch' type expects a non-array constant. A filter clause expects an
5893 // array constant.
5894 if (CT == LandingPadInst::Catch) {
5895 if (isa<ArrayType>(V->getType()))
5896 Error(VLoc, "'catch' clause has an invalid type");
5897 } else {
5898 if (!isa<ArrayType>(V->getType()))
5899 Error(VLoc, "'filter' clause has an invalid type");
5900 }
5901
Owen Andersonf8f259d2015-03-09 07:13:42 +00005902 Constant *CV = dyn_cast<Constant>(V);
5903 if (!CV)
5904 return Error(VLoc, "clause argument must be a constant");
5905 LP->addClause(CV);
Bill Wendlingfae14752011-08-12 20:24:12 +00005906 }
5907
Owen Andersonf8f259d2015-03-09 07:13:42 +00005908 Inst = LP.release();
Bill Wendlingfae14752011-08-12 20:24:12 +00005909 return false;
5910}
5911
Chris Lattnerac161bf2009-01-02 07:01:27 +00005912/// ParseCall
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005913/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5914/// OptionalAttrs Type Value ParameterList OptionalAttrs
5915/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5916/// OptionalAttrs Type Value ParameterList OptionalAttrs
5917/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5918/// OptionalAttrs Type Value ParameterList OptionalAttrs
5919/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5920/// OptionalAttrs Type Value ParameterList OptionalAttrs
Chris Lattnerac161bf2009-01-02 07:01:27 +00005921bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
Reid Kleckner5772b772014-04-24 20:14:34 +00005922 CallInst::TailCallKind TCK) {
Bill Wendling50d27842012-10-15 20:35:56 +00005923 AttrBuilder RetAttrs, FnAttrs;
Bill Wendlingb32b0412013-02-08 06:32:06 +00005924 std::vector<unsigned> FwdRefAttrGrps;
Michael Gottesman41748d72013-06-27 00:25:01 +00005925 LocTy BuiltinLoc;
Alexey Samsonov17a9cff2014-09-10 18:00:17 +00005926 unsigned CC;
Craig Topper2617dcc2014-04-15 06:32:26 +00005927 Type *RetType = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005928 LocTy RetTypeLoc;
5929 ValID CalleeID;
5930 SmallVector<ParamInfo, 16> ArgList;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005931 SmallVector<OperandBundleDef, 2> BundleList;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005932 LocTy CallLoc = Lex.getLoc();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005933
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005934 if (TCK != CallInst::TCK_None &&
5935 ParseToken(lltok::kw_call,
5936 "expected 'tail call', 'musttail call', or 'notail call'"))
5937 return true;
5938
5939 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5940
5941 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
Chris Lattnerf880ca22009-03-09 04:49:14 +00005942 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerac161bf2009-01-02 07:01:27 +00005943 ParseValID(CalleeID) ||
Reid Kleckner83498642014-08-26 00:33:28 +00005944 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5945 PFS.getFunction().isVarArg()) ||
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005946 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5947 ParseOptionalOperandBundles(BundleList, PFS))
Chris Lattnerac161bf2009-01-02 07:01:27 +00005948 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005949
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005950 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5951 return Error(CallLoc, "fast-math-flags specified for call without "
5952 "floating-point scalar or vector return type");
5953
Chris Lattnerac161bf2009-01-02 07:01:27 +00005954 // If RetType is a non-function pointer type, then this is the short syntax
5955 // for the call, which means that RetType is just the return type. Infer the
5956 // rest of the function argument types from the arguments that are present.
David Blaikie23af6482015-04-16 23:24:18 +00005957 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5958 if (!Ty) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00005959 // Pull out the types of all of the arguments...
Jay Foadb804a2b2011-07-12 14:06:48 +00005960 std::vector<Type*> ParamTypes;
Eli Friedman6cf51412010-07-24 23:06:59 +00005961 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5962 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005963
Chris Lattnerac161bf2009-01-02 07:01:27 +00005964 if (!FunctionType::isValidReturnType(RetType))
5965 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005966
Owen Anderson4056ca92009-07-29 22:17:13 +00005967 Ty = FunctionType::get(RetType, ParamTypes, false);
Chris Lattnerac161bf2009-01-02 07:01:27 +00005968 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005969
David Blaikie41ba2b42015-07-27 23:32:19 +00005970 CalleeID.FTy = Ty;
5971
Chris Lattnerac161bf2009-01-02 07:01:27 +00005972 // Look up the callee.
5973 Value *Callee;
David Blaikie23af6482015-04-16 23:24:18 +00005974 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5975 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005976
Bill Wendling3d7b0b82012-12-19 07:18:57 +00005977 // Set up the Attribute for the function.
Bill Wendlingf5075a42013-01-27 02:24:02 +00005978 SmallVector<AttributeSet, 8> Attrs;
Bill Wendling3bef2dd2012-09-19 23:54:18 +00005979 if (RetAttrs.hasAttributes())
Bill Wendlingf5075a42013-01-27 02:24:02 +00005980 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5981 AttributeSet::ReturnIndex,
5982 RetAttrs));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005983
Chris Lattnerac161bf2009-01-02 07:01:27 +00005984 SmallVector<Value*, 8> Args;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005985
Chris Lattnerac161bf2009-01-02 07:01:27 +00005986 // Loop through FunctionType's arguments and ensure they are specified
5987 // correctly. Also, gather any parameter attributes.
5988 FunctionType::param_iterator I = Ty->param_begin();
5989 FunctionType::param_iterator E = Ty->param_end();
5990 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005991 Type *ExpectedTy = nullptr;
Chris Lattnerac161bf2009-01-02 07:01:27 +00005992 if (I != E) {
5993 ExpectedTy = *I++;
5994 } else if (!Ty->isVarArg()) {
5995 return Error(ArgList[i].Loc, "too many arguments specified");
5996 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005997
Chris Lattnerac161bf2009-01-02 07:01:27 +00005998 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5999 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0f214eb2011-06-18 21:18:23 +00006000 getTypeString(ExpectedTy) + "'");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006001 Args.push_back(ArgList[i].V);
Bill Wendlingfe0021a2013-01-31 00:29:54 +00006002 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
6003 AttrBuilder B(ArgList[i].Attrs, i + 1);
Bill Wendlingf5075a42013-01-27 02:24:02 +00006004 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
6005 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006006 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006007
Chris Lattnerac161bf2009-01-02 07:01:27 +00006008 if (I != E)
6009 return Error(CallLoc, "not enough parameters specified for call");
6010
David Majnemer8d22abd2015-02-23 00:01:32 +00006011 if (FnAttrs.hasAttributes()) {
6012 if (FnAttrs.hasAlignmentAttr())
6013 return Error(CallLoc, "call instructions may not have an alignment");
6014
Bill Wendlingf5075a42013-01-27 02:24:02 +00006015 Attrs.push_back(AttributeSet::get(RetType->getContext(),
6016 AttributeSet::FunctionIndex,
6017 FnAttrs));
David Majnemer8d22abd2015-02-23 00:01:32 +00006018 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006019
Bill Wendling3d7b0b82012-12-19 07:18:57 +00006020 // Finish off the Attribute and check them
Bill Wendlinge94d8432012-12-07 23:16:57 +00006021 AttributeSet PAL = AttributeSet::get(Context, Attrs);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006022
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00006023 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
Reid Kleckner5772b772014-04-24 20:14:34 +00006024 CI->setTailCallKind(TCK);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006025 CI->setCallingConv(CC);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00006026 if (FMF.any())
6027 CI->setFastMathFlags(FMF);
Chris Lattnerac161bf2009-01-02 07:01:27 +00006028 CI->setAttributes(PAL);
Bill Wendlingb32b0412013-02-08 06:32:06 +00006029 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006030 Inst = CI;
6031 return false;
6032}
6033
6034//===----------------------------------------------------------------------===//
6035// Memory Instructions.
6036//===----------------------------------------------------------------------===//
6037
6038/// ParseAlloc
Manman Ren9bfd0d02016-04-01 21:41:15 +00006039/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6040/// (',' 'align' i32)?
Chris Lattner78103722011-06-17 03:16:47 +00006041int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006042 Value *Size = nullptr;
David Majnemera3b0eb22015-02-16 08:38:03 +00006043 LocTy SizeLoc, TyLoc;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006044 unsigned Alignment = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00006045 Type *Ty = nullptr;
David Majnemerc4ab61c2014-03-09 06:41:58 +00006046
6047 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006048 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
David Majnemerc4ab61c2014-03-09 06:41:58 +00006049
David Majnemera3b0eb22015-02-16 08:38:03 +00006050 if (ParseType(Ty, TyLoc)) return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006051
David Majnemera3b0eb22015-02-16 08:38:03 +00006052 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6053 return Error(TyLoc, "invalid type for alloca");
David Majnemerfad5a312015-02-11 09:13:11 +00006054
Chris Lattnerb2f39502009-12-30 05:44:30 +00006055 bool AteExtraComma = false;
Chris Lattner3822f632009-01-02 08:05:26 +00006056 if (EatIfPresent(lltok::comma)) {
David Majnemerc4ab61c2014-03-09 06:41:58 +00006057 if (Lex.getKind() == lltok::kw_align) {
6058 if (ParseOptionalAlignment(Alignment)) return true;
6059 } else if (Lex.getKind() == lltok::MetadataVar) {
6060 AteExtraComma = true;
6061 } else {
6062 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
6063 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6064 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006065 }
6066 }
6067
Dan Gohman2140a742010-05-28 01:14:11 +00006068 if (Size && !Size->getType()->isIntegerTy())
6069 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006070
Reid Kleckner436c42e2014-01-17 23:58:17 +00006071 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
6072 AI->setUsedWithInAlloca(IsInAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00006073 AI->setSwiftError(IsSwiftError);
Reid Kleckner436c42e2014-01-17 23:58:17 +00006074 Inst = AI;
Chris Lattner78103722011-06-17 03:16:47 +00006075 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006076}
6077
6078/// ParseLoad
Eli Friedman02e737b2011-08-12 22:50:01 +00006079/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006080/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
Eli Friedman02e737b2011-08-12 22:50:01 +00006081/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006082int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006083 Value *Val; LocTy Loc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006084 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006085 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006086 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006087 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006088 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006089
6090 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006091 isAtomic = true;
6092 Lex.Lex();
6093 }
6094
Chris Lattnerbc639292011-11-27 06:56:53 +00006095 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006096 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006097 isVolatile = true;
6098 Lex.Lex();
6099 }
6100
David Blaikie15d9a4c2015-04-06 20:59:48 +00006101 Type *Ty;
David Blaikiea79ac142015-02-27 21:17:42 +00006102 LocTy ExplicitTypeLoc = Lex.getLoc();
6103 if (ParseType(Ty) ||
6104 ParseToken(lltok::comma, "expected comma after load's type") ||
6105 ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006106 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006107 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6108 return true;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006109
David Blaikie15d9a4c2015-04-06 20:59:48 +00006110 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006111 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman59b66882011-08-09 23:02:53 +00006112 if (isAtomic && !Alignment)
6113 return Error(Loc, "atomic load must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006114 if (Ordering == AtomicOrdering::Release ||
6115 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006116 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006117
David Blaikiea79ac142015-02-27 21:17:42 +00006118 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6119 return Error(ExplicitTypeLoc,
6120 "explicit pointee type doesn't match operand's pointee type");
6121
David Blaikie15d9a4c2015-04-06 20:59:48 +00006122 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006123 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006124}
6125
6126/// ParseStore
Eli Friedman02e737b2011-08-12 22:50:01 +00006127
6128/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6129/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman59b66882011-08-09 23:02:53 +00006130/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerbc639292011-11-27 06:56:53 +00006131int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006132 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelea8a4b92009-09-17 23:04:48 +00006133 unsigned Alignment = 0;
Chris Lattnerb2f39502009-12-30 05:44:30 +00006134 bool AteExtraComma = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006135 bool isAtomic = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006136 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedman59b66882011-08-09 23:02:53 +00006137 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006138
6139 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006140 isAtomic = true;
6141 Lex.Lex();
6142 }
6143
Chris Lattnerbc639292011-11-27 06:56:53 +00006144 bool isVolatile = false;
Eli Friedman02e737b2011-08-12 22:50:01 +00006145 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedman02e737b2011-08-12 22:50:01 +00006146 isVolatile = true;
6147 Lex.Lex();
6148 }
6149
Chris Lattnerac161bf2009-01-02 07:01:27 +00006150 if (ParseTypeAndValue(Val, Loc, PFS) ||
6151 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006152 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman59b66882011-08-09 23:02:53 +00006153 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerb2f39502009-12-30 05:44:30 +00006154 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006155 return true;
Devang Patelea8a4b92009-09-17 23:04:48 +00006156
Duncan Sands19d0b472010-02-16 11:11:14 +00006157 if (!Ptr->getType()->isPointerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006158 return Error(PtrLoc, "store operand must be a pointer");
6159 if (!Val->getType()->isFirstClassType())
6160 return Error(Loc, "store operand must be a first class value");
6161 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6162 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman59b66882011-08-09 23:02:53 +00006163 if (isAtomic && !Alignment)
6164 return Error(Loc, "atomic store must have explicit non-zero alignment");
JF Bastien800f87a2016-04-06 21:19:33 +00006165 if (Ordering == AtomicOrdering::Acquire ||
6166 Ordering == AtomicOrdering::AcquireRelease)
Eli Friedman59b66882011-08-09 23:02:53 +00006167 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006168
Eli Friedman59b66882011-08-09 23:02:53 +00006169 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerb2f39502009-12-30 05:44:30 +00006170 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006171}
6172
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006173/// ParseCmpXchg
Tim Northover420a2162014-06-13 14:24:07 +00006174/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6175/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
Eli Friedman02e737b2011-08-12 22:50:01 +00006176int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006177 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6178 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006179 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6180 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006181 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006182 bool isVolatile = false;
Tim Northover420a2162014-06-13 14:24:07 +00006183 bool isWeak = false;
6184
6185 if (EatIfPresent(lltok::kw_weak))
6186 isWeak = true;
Eli Friedman02e737b2011-08-12 22:50:01 +00006187
6188 if (EatIfPresent(lltok::kw_volatile))
6189 isVolatile = true;
6190
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006191 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6192 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6193 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6194 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6195 ParseTypeAndValue(New, NewLoc, PFS) ||
Tim Northovere94a5182014-03-11 10:48:52 +00006196 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6197 ParseOrdering(FailureOrdering))
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006198 return true;
6199
JF Bastien800f87a2016-04-06 21:19:33 +00006200 if (SuccessOrdering == AtomicOrdering::Unordered ||
6201 FailureOrdering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006202 return TokError("cmpxchg cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006203 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6204 return TokError("cmpxchg failure argument shall be no stronger than the "
6205 "success argument");
6206 if (FailureOrdering == AtomicOrdering::Release ||
6207 FailureOrdering == AtomicOrdering::AcquireRelease)
6208 return TokError(
6209 "cmpxchg failure ordering cannot include release semantics");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006210 if (!Ptr->getType()->isPointerTy())
6211 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6212 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6213 return Error(CmpLoc, "compare value and pointer type do not match");
6214 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6215 return Error(NewLoc, "new value and pointer type do not match");
Philip Reames1960cfd2016-02-19 00:06:41 +00006216 if (!New->getType()->isFirstClassType())
6217 return Error(NewLoc, "cmpxchg operand must be a first class value");
Tim Northover420a2162014-06-13 14:24:07 +00006218 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6219 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006220 CXI->setVolatile(isVolatile);
Tim Northover420a2162014-06-13 14:24:07 +00006221 CXI->setWeak(isWeak);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006222 Inst = CXI;
6223 return AteExtraComma ? InstExtraComma : InstNormal;
6224}
6225
6226/// ParseAtomicRMW
Eli Friedman02e737b2011-08-12 22:50:01 +00006227/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6228/// 'singlethread'? AtomicOrdering
6229int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006230 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6231 bool AteExtraComma = false;
JF Bastien800f87a2016-04-06 21:19:33 +00006232 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006233 SynchronizationScope Scope = CrossThread;
Eli Friedman02e737b2011-08-12 22:50:01 +00006234 bool isVolatile = false;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006235 AtomicRMWInst::BinOp Operation;
Eli Friedman02e737b2011-08-12 22:50:01 +00006236
6237 if (EatIfPresent(lltok::kw_volatile))
6238 isVolatile = true;
6239
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006240 switch (Lex.getKind()) {
6241 default: return TokError("expected binary operation in atomicrmw");
6242 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6243 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6244 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6245 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6246 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6247 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6248 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6249 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6250 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6251 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6252 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6253 }
6254 Lex.Lex(); // Eat the operation.
6255
6256 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6257 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6258 ParseTypeAndValue(Val, ValLoc, PFS) ||
6259 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6260 return true;
6261
JF Bastien800f87a2016-04-06 21:19:33 +00006262 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanc9a551e2011-07-28 21:48:00 +00006263 return TokError("atomicrmw cannot be unordered");
6264 if (!Ptr->getType()->isPointerTy())
6265 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6266 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6267 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6268 if (!Val->getType()->isIntegerTy())
6269 return Error(ValLoc, "atomicrmw operand must be an integer");
6270 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6271 if (Size < 8 || (Size & (Size - 1)))
6272 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6273 " integer");
6274
6275 AtomicRMWInst *RMWI =
6276 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6277 RMWI->setVolatile(isVolatile);
6278 Inst = RMWI;
6279 return AteExtraComma ? InstExtraComma : InstNormal;
6280}
6281
Eli Friedmanfee02c62011-07-25 23:16:38 +00006282/// ParseFence
6283/// ::= 'fence' 'singlethread'? AtomicOrdering
6284int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
JF Bastien800f87a2016-04-06 21:19:33 +00006285 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
Eli Friedmanfee02c62011-07-25 23:16:38 +00006286 SynchronizationScope Scope = CrossThread;
6287 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6288 return true;
6289
JF Bastien800f87a2016-04-06 21:19:33 +00006290 if (Ordering == AtomicOrdering::Unordered)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006291 return TokError("fence cannot be unordered");
JF Bastien800f87a2016-04-06 21:19:33 +00006292 if (Ordering == AtomicOrdering::Monotonic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00006293 return TokError("fence cannot be monotonic");
6294
6295 Inst = new FenceInst(Context, Ordering, Scope);
6296 return InstNormal;
6297}
6298
Chris Lattnerac161bf2009-01-02 07:01:27 +00006299/// ParseGetElementPtr
Dan Gohman1639c392009-07-27 21:53:46 +00006300/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerf4f03422009-12-30 05:27:33 +00006301int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006302 Value *Ptr = nullptr;
6303 Value *Val = nullptr;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006304 LocTy Loc, EltLoc;
Dan Gohman1639c392009-07-27 21:53:46 +00006305
Dan Gohman16cbbe42009-07-29 15:58:36 +00006306 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohman1639c392009-07-27 21:53:46 +00006307
David Blaikie79e6c742015-02-27 19:29:02 +00006308 Type *Ty = nullptr;
6309 LocTy ExplicitTypeLoc = Lex.getLoc();
6310 if (ParseType(Ty) ||
6311 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6312 ParseTypeAndValue(Ptr, Loc, PFS))
6313 return true;
6314
Eli Benderskyd9806682013-04-22 17:03:42 +00006315 Type *BaseType = Ptr->getType();
6316 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6317 if (!BasePointerType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006318 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006319
David Blaikie8d757942015-03-09 23:08:44 +00006320 if (Ty != BasePointerType->getElementType())
6321 return Error(ExplicitTypeLoc,
6322 "explicit pointee type doesn't match operand's pointee type");
6323
Chris Lattnerac161bf2009-01-02 07:01:27 +00006324 SmallVector<Value*, 16> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006325 bool AteExtraComma = false;
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006326 // GEP returns a vector of pointers if at least one of parameters is a vector.
6327 // All vector parameters should have the same vector width.
6328 unsigned GEPWidth = BaseType->isVectorTy() ?
6329 BaseType->getVectorNumElements() : 0;
6330
Chris Lattner3822f632009-01-02 08:05:26 +00006331 while (EatIfPresent(lltok::comma)) {
Chris Lattnerf4f03422009-12-30 05:27:33 +00006332 if (Lex.getKind() == lltok::MetadataVar) {
6333 AteExtraComma = true;
Devang Patel52b17452009-10-13 18:49:55 +00006334 break;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006335 }
Chris Lattner3822f632009-01-02 08:05:26 +00006336 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006337 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerac161bf2009-01-02 07:01:27 +00006338 return Error(EltLoc, "getelementptr index must be an integer");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006339
Nadav Rotem3924cb02011-12-05 06:29:09 +00006340 if (Val->getType()->isVectorTy()) {
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006341 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6342 if (GEPWidth && GEPWidth != ValNumEl)
Nadav Rotem3924cb02011-12-05 06:29:09 +00006343 return Error(EltLoc,
6344 "getelementptr vector index has a wrong number of elements");
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00006345 GEPWidth = ValNumEl;
Nadav Rotem3924cb02011-12-05 06:29:09 +00006346 }
Chris Lattnerac161bf2009-01-02 07:01:27 +00006347 Indices.push_back(Val);
6348 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006349
Craig Toppere3dcce92015-08-01 22:20:21 +00006350 SmallPtrSet<Type*, 4> Visited;
David Blaikied33bad32015-04-17 22:32:13 +00006351 if (!Indices.empty() && !Ty->isSized(&Visited))
Eli Benderskyd9806682013-04-22 17:03:42 +00006352 return Error(Loc, "base element of getelementptr must be sized");
6353
David Blaikied33bad32015-04-17 22:32:13 +00006354 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006355 return Error(Loc, "invalid getelementptr indices");
David Blaikiecd7b97e2015-03-14 21:11:24 +00006356 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
Dan Gohman1639c392009-07-27 21:53:46 +00006357 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00006358 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006359 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006360}
6361
6362/// ParseExtractValue
6363/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006364int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006365 Value *Val; LocTy Loc;
6366 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006367 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006368 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006369 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006370 return true;
6371
Chris Lattner392be582010-02-12 20:49:41 +00006372 if (!Val->getType()->isAggregateType())
6373 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerac161bf2009-01-02 07:01:27 +00006374
Jay Foad57aa6362011-07-13 10:26:04 +00006375 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006376 return Error(Loc, "invalid indices for extractvalue");
Jay Foad57aa6362011-07-13 10:26:04 +00006377 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006378 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006379}
6380
6381/// ParseInsertValue
6382/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnerf4f03422009-12-30 05:27:33 +00006383int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerac161bf2009-01-02 07:01:27 +00006384 Value *Val0, *Val1; LocTy Loc0, Loc1;
6385 SmallVector<unsigned, 4> Indices;
Chris Lattnerf4f03422009-12-30 05:27:33 +00006386 bool AteExtraComma;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006387 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6388 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6389 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnerf4f03422009-12-30 05:27:33 +00006390 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerac161bf2009-01-02 07:01:27 +00006391 return true;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006392
Chris Lattner392be582010-02-12 20:49:41 +00006393 if (!Val0->getType()->isAggregateType())
6394 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00006395
David Majnemer30074532015-02-11 07:43:58 +00006396 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6397 if (!IndexedType)
Chris Lattnerac161bf2009-01-02 07:01:27 +00006398 return Error(Loc0, "invalid indices for insertvalue");
David Majnemer30074532015-02-11 07:43:58 +00006399 if (IndexedType != Val1->getType())
6400 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6401 getTypeString(Val1->getType()) + "' instead of '" +
6402 getTypeString(IndexedType) + "'");
Jay Foad57aa6362011-07-13 10:26:04 +00006403 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnerf4f03422009-12-30 05:27:33 +00006404 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerac161bf2009-01-02 07:01:27 +00006405}
Nick Lewycky49f89192009-04-04 07:22:01 +00006406
6407//===----------------------------------------------------------------------===//
6408// Embedded metadata.
6409//===----------------------------------------------------------------------===//
6410
6411/// ParseMDNodeVector
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006412/// ::= { Element (',' Element)* }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006413/// Element
6414/// ::= 'null' | TypeAndValue
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006415bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
David Majnemer06f960d2014-12-11 20:44:09 +00006416 if (ParseToken(lltok::lbrace, "expected '{' here"))
6417 return true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006418
Dan Gohman1e0213a2010-07-13 19:33:27 +00006419 // Check for an empty list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006420 if (EatIfPresent(lltok::rbrace))
Dan Gohman1e0213a2010-07-13 19:33:27 +00006421 return false;
6422
Nick Lewycky49f89192009-04-04 07:22:01 +00006423 do {
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006424 // Null is a special case since it is typeless.
6425 if (EatIfPresent(lltok::kw_null)) {
Craig Topper2617dcc2014-04-15 06:32:26 +00006426 Elts.push_back(nullptr);
Chris Lattnera01ddfc2009-12-30 04:42:57 +00006427 continue;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00006428 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00006429
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006430 Metadata *MD;
6431 if (ParseMetadata(MD, nullptr))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006432 return true;
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00006433 Elts.push_back(MD);
Nick Lewycky49f89192009-04-04 07:22:01 +00006434 } while (EatIfPresent(lltok::comma));
6435
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00006436 return ParseToken(lltok::rbrace, "expected end of metadata node");
Nick Lewycky49f89192009-04-04 07:22:01 +00006437}
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006438
6439//===----------------------------------------------------------------------===//
6440// Use-list order directives.
6441//===----------------------------------------------------------------------===//
6442bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6443 SMLoc Loc) {
6444 if (V->use_empty())
6445 return Error(Loc, "value has no uses");
6446
6447 unsigned NumUses = 0;
6448 SmallDenseMap<const Use *, unsigned, 16> Order;
6449 for (const Use &U : V->uses()) {
6450 if (++NumUses > Indexes.size())
6451 break;
6452 Order[&U] = Indexes[NumUses - 1];
6453 }
6454 if (NumUses < 2)
6455 return Error(Loc, "value only has one use");
6456 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6457 return Error(Loc, "wrong number of indexes, expected " +
6458 Twine(std::distance(V->use_begin(), V->use_end())));
6459
6460 V->sortUseList([&](const Use &L, const Use &R) {
6461 return Order.lookup(&L) < Order.lookup(&R);
6462 });
6463 return false;
6464}
6465
6466/// ParseUseListOrderIndexes
6467/// ::= '{' uint32 (',' uint32)+ '}'
6468bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6469 SMLoc Loc = Lex.getLoc();
6470 if (ParseToken(lltok::lbrace, "expected '{' here"))
6471 return true;
6472 if (Lex.getKind() == lltok::rbrace)
6473 return Lex.Error("expected non-empty list of uselistorder indexes");
6474
6475 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6476 // indexes should be distinct numbers in the range [0, size-1], and should
6477 // not be in order.
6478 unsigned Offset = 0;
6479 unsigned Max = 0;
6480 bool IsOrdered = true;
6481 assert(Indexes.empty() && "Expected empty order vector");
6482 do {
6483 unsigned Index;
6484 if (ParseUInt32(Index))
6485 return true;
6486
6487 // Update consistency checks.
6488 Offset += Index - Indexes.size();
6489 Max = std::max(Max, Index);
6490 IsOrdered &= Index == Indexes.size();
6491
6492 Indexes.push_back(Index);
6493 } while (EatIfPresent(lltok::comma));
6494
6495 if (ParseToken(lltok::rbrace, "expected '}' here"))
6496 return true;
6497
6498 if (Indexes.size() < 2)
6499 return Error(Loc, "expected >= 2 uselistorder indexes");
6500 if (Offset != 0 || Max >= Indexes.size())
6501 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6502 if (IsOrdered)
6503 return Error(Loc, "expected uselistorder indexes to change the order");
6504
6505 return false;
6506}
6507
6508/// ParseUseListOrder
6509/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6510bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6511 SMLoc Loc = Lex.getLoc();
6512 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6513 return true;
6514
6515 Value *V;
6516 SmallVector<unsigned, 16> Indexes;
6517 if (ParseTypeAndValue(V, PFS) ||
6518 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6519 ParseUseListOrderIndexes(Indexes))
6520 return true;
6521
6522 return sortUseListOrder(V, Indexes, Loc);
6523}
6524
6525/// ParseUseListOrderBB
6526/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6527bool LLParser::ParseUseListOrderBB() {
6528 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6529 SMLoc Loc = Lex.getLoc();
6530 Lex.Lex();
6531
6532 ValID Fn, Label;
6533 SmallVector<unsigned, 16> Indexes;
6534 if (ParseValID(Fn) ||
6535 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6536 ParseValID(Label) ||
6537 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6538 ParseUseListOrderIndexes(Indexes))
6539 return true;
6540
6541 // Check the function.
6542 GlobalValue *GV;
6543 if (Fn.Kind == ValID::t_GlobalName)
6544 GV = M->getNamedValue(Fn.StrVal);
6545 else if (Fn.Kind == ValID::t_GlobalID)
6546 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6547 else
6548 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6549 if (!GV)
6550 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6551 auto *F = dyn_cast<Function>(GV);
6552 if (!F)
6553 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6554 if (F->isDeclaration())
6555 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6556
6557 // Check the basic block.
6558 if (Label.Kind == ValID::t_LocalID)
6559 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6560 if (Label.Kind != ValID::t_LocalName)
6561 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
Mehdi Aminia53d49e2016-09-17 06:00:02 +00006562 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00006563 if (!V)
6564 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6565 if (!isa<BasicBlock>(V))
6566 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6567
6568 return sortUseListOrder(V, Indexes, Loc);
6569}