Bug Summary

File:src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/AsmParser/LLParser.cpp
Warning:line 3282, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name LLParser.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 1 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Analysis -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ASMParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/BinaryFormat -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitstream -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /include/llvm/CodeGen -I /include/llvm/CodeGen/PBQP -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Coroutines -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData/Coverage -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/CodeView -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/DWARF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/MSF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/PDB -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Demangle -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/JITLink -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/Orc -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenACC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenMP -I /include/llvm/CodeGen/GlobalISel -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IRReader -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/LTO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Linker -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC/MCParser -I /include/llvm/CodeGen/MIRParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Object -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Option -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Passes -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Scalar -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ADT -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/Symbolize -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Target -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Utils -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Vectorize -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/IPO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libLLVM/../include -I /usr/src/gnu/usr.bin/clang/libLLVM/obj -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -D PIC -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -D_RET_PROTECTOR -ret-protector -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/AsmParser/LLParser.cpp
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/AsmParser/LLParser.h"
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/AsmParser/LLToken.h"
20#include "llvm/AsmParser/SlotMapping.h"
21#include "llvm/BinaryFormat/Dwarf.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/AutoUpgrade.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Comdat.h"
27#include "llvm/IR/ConstantRange.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DebugInfoMetadata.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/GlobalIFunc.h"
33#include "llvm/IR/GlobalObject.h"
34#include "llvm/IR/InlineAsm.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/LLVMContext.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
40#include "llvm/IR/Value.h"
41#include "llvm/IR/ValueSymbolTable.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/MathExtras.h"
45#include "llvm/Support/SaveAndRestore.h"
46#include "llvm/Support/raw_ostream.h"
47#include <algorithm>
48#include <cassert>
49#include <cstring>
50#include <iterator>
51#include <vector>
52
53using namespace llvm;
54
55static std::string getTypeString(Type *T) {
56 std::string Result;
57 raw_string_ostream Tmp(Result);
58 Tmp << *T;
59 return Tmp.str();
60}
61
62/// Run: module ::= toplevelentity*
63bool LLParser::Run(bool UpgradeDebugInfo,
64 DataLayoutCallbackTy DataLayoutCallback) {
65 // Prime the lexer.
66 Lex.Lex();
67
68 if (Context.shouldDiscardValueNames())
69 return error(
70 Lex.getLoc(),
71 "Can't read textual IR with a Context that discards named Values");
72
73 if (M) {
74 if (parseTargetDefinitions())
75 return true;
76
77 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple()))
78 M->setDataLayout(*LayoutOverride);
79 }
80
81 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
82 validateEndOfIndex();
83}
84
85bool LLParser::parseStandaloneConstantValue(Constant *&C,
86 const SlotMapping *Slots) {
87 restoreParsingState(Slots);
88 Lex.Lex();
89
90 Type *Ty = nullptr;
91 if (parseType(Ty) || parseConstantValue(Ty, C))
92 return true;
93 if (Lex.getKind() != lltok::Eof)
94 return error(Lex.getLoc(), "expected end of string");
95 return false;
96}
97
98bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
99 const SlotMapping *Slots) {
100 restoreParsingState(Slots);
101 Lex.Lex();
102
103 Read = 0;
104 SMLoc Start = Lex.getLoc();
105 Ty = nullptr;
106 if (parseType(Ty))
107 return true;
108 SMLoc End = Lex.getLoc();
109 Read = End.getPointer() - Start.getPointer();
110
111 return false;
112}
113
114void LLParser::restoreParsingState(const SlotMapping *Slots) {
115 if (!Slots)
116 return;
117 NumberedVals = Slots->GlobalValues;
118 NumberedMetadata = Slots->MetadataNodes;
119 for (const auto &I : Slots->NamedTypes)
120 NamedTypes.insert(
121 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
122 for (const auto &I : Slots->Types)
123 NumberedTypes.insert(
124 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
125}
126
127/// validateEndOfModule - Do final validity and sanity checks at the end of the
128/// module.
129bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
130 if (!M)
131 return false;
132 // Handle any function attribute group forward references.
133 for (const auto &RAG : ForwardRefAttrGroups) {
134 Value *V = RAG.first;
135 const std::vector<unsigned> &Attrs = RAG.second;
136 AttrBuilder B;
137
138 for (const auto &Attr : Attrs)
139 B.merge(NumberedAttrBuilders[Attr]);
140
141 if (Function *Fn = dyn_cast<Function>(V)) {
142 AttributeList AS = Fn->getAttributes();
143 AttrBuilder FnAttrs(AS.getFnAttributes());
144 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
145
146 FnAttrs.merge(B);
147
148 // If the alignment was parsed as an attribute, move to the alignment
149 // field.
150 if (FnAttrs.hasAlignmentAttr()) {
151 Fn->setAlignment(FnAttrs.getAlignment());
152 FnAttrs.removeAttribute(Attribute::Alignment);
153 }
154
155 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
156 AttributeSet::get(Context, FnAttrs));
157 Fn->setAttributes(AS);
158 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
159 AttributeList AS = CI->getAttributes();
160 AttrBuilder FnAttrs(AS.getFnAttributes());
161 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
162 FnAttrs.merge(B);
163 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
164 AttributeSet::get(Context, FnAttrs));
165 CI->setAttributes(AS);
166 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
167 AttributeList AS = II->getAttributes();
168 AttrBuilder FnAttrs(AS.getFnAttributes());
169 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
170 FnAttrs.merge(B);
171 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
172 AttributeSet::get(Context, FnAttrs));
173 II->setAttributes(AS);
174 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
175 AttributeList AS = CBI->getAttributes();
176 AttrBuilder FnAttrs(AS.getFnAttributes());
177 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
178 FnAttrs.merge(B);
179 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
180 AttributeSet::get(Context, FnAttrs));
181 CBI->setAttributes(AS);
182 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
183 AttrBuilder Attrs(GV->getAttributes());
184 Attrs.merge(B);
185 GV->setAttributes(AttributeSet::get(Context,Attrs));
186 } else {
187 llvm_unreachable("invalid object with forward attribute group reference")__builtin_unreachable();
188 }
189 }
190
191 // If there are entries in ForwardRefBlockAddresses at this point, the
192 // function was never defined.
193 if (!ForwardRefBlockAddresses.empty())
194 return error(ForwardRefBlockAddresses.begin()->first.Loc,
195 "expected function name in blockaddress");
196
197 for (const auto &NT : NumberedTypes)
198 if (NT.second.second.isValid())
199 return error(NT.second.second,
200 "use of undefined type '%" + Twine(NT.first) + "'");
201
202 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
203 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
204 if (I->second.second.isValid())
205 return error(I->second.second,
206 "use of undefined type named '" + I->getKey() + "'");
207
208 if (!ForwardRefComdats.empty())
209 return error(ForwardRefComdats.begin()->second,
210 "use of undefined comdat '$" +
211 ForwardRefComdats.begin()->first + "'");
212
213 if (!ForwardRefVals.empty())
214 return error(ForwardRefVals.begin()->second.second,
215 "use of undefined value '@" + ForwardRefVals.begin()->first +
216 "'");
217
218 if (!ForwardRefValIDs.empty())
219 return error(ForwardRefValIDs.begin()->second.second,
220 "use of undefined value '@" +
221 Twine(ForwardRefValIDs.begin()->first) + "'");
222
223 if (!ForwardRefMDNodes.empty())
224 return error(ForwardRefMDNodes.begin()->second.second,
225 "use of undefined metadata '!" +
226 Twine(ForwardRefMDNodes.begin()->first) + "'");
227
228 // Resolve metadata cycles.
229 for (auto &N : NumberedMetadata) {
230 if (N.second && !N.second->isResolved())
231 N.second->resolveCycles();
232 }
233
234 for (auto *Inst : InstsWithTBAATag) {
235 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
236 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag")((void)0);
237 auto *UpgradedMD = UpgradeTBAANode(*MD);
238 if (MD != UpgradedMD)
239 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
240 }
241
242 // Look for intrinsic functions and CallInst that need to be upgraded
243 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
244 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
245
246 // Some types could be renamed during loading if several modules are
247 // loaded in the same LLVMContext (LTO scenario). In this case we should
248 // remangle intrinsics names as well.
249 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
250 Function *F = &*FI++;
251 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
252 F->replaceAllUsesWith(Remangled.getValue());
253 F->eraseFromParent();
254 }
255 }
256
257 if (UpgradeDebugInfo)
258 llvm::UpgradeDebugInfo(*M);
259
260 UpgradeModuleFlags(*M);
261 UpgradeSectionAttributes(*M);
262
263 if (!Slots)
264 return false;
265 // Initialize the slot mapping.
266 // Because by this point we've parsed and validated everything, we can "steal"
267 // the mapping from LLParser as it doesn't need it anymore.
268 Slots->GlobalValues = std::move(NumberedVals);
269 Slots->MetadataNodes = std::move(NumberedMetadata);
270 for (const auto &I : NamedTypes)
271 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
272 for (const auto &I : NumberedTypes)
273 Slots->Types.insert(std::make_pair(I.first, I.second.first));
274
275 return false;
276}
277
278/// Do final validity and sanity checks at the end of the index.
279bool LLParser::validateEndOfIndex() {
280 if (!Index)
281 return false;
282
283 if (!ForwardRefValueInfos.empty())
284 return error(ForwardRefValueInfos.begin()->second.front().second,
285 "use of undefined summary '^" +
286 Twine(ForwardRefValueInfos.begin()->first) + "'");
287
288 if (!ForwardRefAliasees.empty())
289 return error(ForwardRefAliasees.begin()->second.front().second,
290 "use of undefined summary '^" +
291 Twine(ForwardRefAliasees.begin()->first) + "'");
292
293 if (!ForwardRefTypeIds.empty())
294 return error(ForwardRefTypeIds.begin()->second.front().second,
295 "use of undefined type id summary '^" +
296 Twine(ForwardRefTypeIds.begin()->first) + "'");
297
298 return false;
299}
300
301//===----------------------------------------------------------------------===//
302// Top-Level Entities
303//===----------------------------------------------------------------------===//
304
305bool LLParser::parseTargetDefinitions() {
306 while (true) {
307 switch (Lex.getKind()) {
308 case lltok::kw_target:
309 if (parseTargetDefinition())
310 return true;
311 break;
312 case lltok::kw_source_filename:
313 if (parseSourceFileName())
314 return true;
315 break;
316 default:
317 return false;
318 }
319 }
320}
321
322bool LLParser::parseTopLevelEntities() {
323 // If there is no Module, then parse just the summary index entries.
324 if (!M) {
325 while (true) {
326 switch (Lex.getKind()) {
327 case lltok::Eof:
328 return false;
329 case lltok::SummaryID:
330 if (parseSummaryEntry())
331 return true;
332 break;
333 case lltok::kw_source_filename:
334 if (parseSourceFileName())
335 return true;
336 break;
337 default:
338 // Skip everything else
339 Lex.Lex();
340 }
341 }
342 }
343 while (true) {
344 switch (Lex.getKind()) {
345 default:
346 return tokError("expected top-level entity");
347 case lltok::Eof: return false;
348 case lltok::kw_declare:
349 if (parseDeclare())
350 return true;
351 break;
352 case lltok::kw_define:
353 if (parseDefine())
354 return true;
355 break;
356 case lltok::kw_module:
357 if (parseModuleAsm())
358 return true;
359 break;
360 case lltok::LocalVarID:
361 if (parseUnnamedType())
362 return true;
363 break;
364 case lltok::LocalVar:
365 if (parseNamedType())
366 return true;
367 break;
368 case lltok::GlobalID:
369 if (parseUnnamedGlobal())
370 return true;
371 break;
372 case lltok::GlobalVar:
373 if (parseNamedGlobal())
374 return true;
375 break;
376 case lltok::ComdatVar: if (parseComdat()) return true; break;
377 case lltok::exclaim:
378 if (parseStandaloneMetadata())
379 return true;
380 break;
381 case lltok::SummaryID:
382 if (parseSummaryEntry())
383 return true;
384 break;
385 case lltok::MetadataVar:
386 if (parseNamedMetadata())
387 return true;
388 break;
389 case lltok::kw_attributes:
390 if (parseUnnamedAttrGrp())
391 return true;
392 break;
393 case lltok::kw_uselistorder:
394 if (parseUseListOrder())
395 return true;
396 break;
397 case lltok::kw_uselistorder_bb:
398 if (parseUseListOrderBB())
399 return true;
400 break;
401 }
402 }
403}
404
405/// toplevelentity
406/// ::= 'module' 'asm' STRINGCONSTANT
407bool LLParser::parseModuleAsm() {
408 assert(Lex.getKind() == lltok::kw_module)((void)0);
409 Lex.Lex();
410
411 std::string AsmStr;
412 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
413 parseStringConstant(AsmStr))
414 return true;
415
416 M->appendModuleInlineAsm(AsmStr);
417 return false;
418}
419
420/// toplevelentity
421/// ::= 'target' 'triple' '=' STRINGCONSTANT
422/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
423bool LLParser::parseTargetDefinition() {
424 assert(Lex.getKind() == lltok::kw_target)((void)0);
425 std::string Str;
426 switch (Lex.Lex()) {
427 default:
428 return tokError("unknown target property");
429 case lltok::kw_triple:
430 Lex.Lex();
431 if (parseToken(lltok::equal, "expected '=' after target triple") ||
432 parseStringConstant(Str))
433 return true;
434 M->setTargetTriple(Str);
435 return false;
436 case lltok::kw_datalayout:
437 Lex.Lex();
438 if (parseToken(lltok::equal, "expected '=' after target datalayout") ||
439 parseStringConstant(Str))
440 return true;
441 M->setDataLayout(Str);
442 return false;
443 }
444}
445
446/// toplevelentity
447/// ::= 'source_filename' '=' STRINGCONSTANT
448bool LLParser::parseSourceFileName() {
449 assert(Lex.getKind() == lltok::kw_source_filename)((void)0);
450 Lex.Lex();
451 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
452 parseStringConstant(SourceFileName))
453 return true;
454 if (M)
455 M->setSourceFileName(SourceFileName);
456 return false;
457}
458
459/// parseUnnamedType:
460/// ::= LocalVarID '=' 'type' type
461bool LLParser::parseUnnamedType() {
462 LocTy TypeLoc = Lex.getLoc();
463 unsigned TypeID = Lex.getUIntVal();
464 Lex.Lex(); // eat LocalVarID;
465
466 if (parseToken(lltok::equal, "expected '=' after name") ||
467 parseToken(lltok::kw_type, "expected 'type' after '='"))
468 return true;
469
470 Type *Result = nullptr;
471 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
472 return true;
473
474 if (!isa<StructType>(Result)) {
475 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
476 if (Entry.first)
477 return error(TypeLoc, "non-struct types may not be recursive");
478 Entry.first = Result;
479 Entry.second = SMLoc();
480 }
481
482 return false;
483}
484
485/// toplevelentity
486/// ::= LocalVar '=' 'type' type
487bool LLParser::parseNamedType() {
488 std::string Name = Lex.getStrVal();
489 LocTy NameLoc = Lex.getLoc();
490 Lex.Lex(); // eat LocalVar.
491
492 if (parseToken(lltok::equal, "expected '=' after name") ||
493 parseToken(lltok::kw_type, "expected 'type' after name"))
494 return true;
495
496 Type *Result = nullptr;
497 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
498 return true;
499
500 if (!isa<StructType>(Result)) {
501 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
502 if (Entry.first)
503 return error(NameLoc, "non-struct types may not be recursive");
504 Entry.first = Result;
505 Entry.second = SMLoc();
506 }
507
508 return false;
509}
510
511/// toplevelentity
512/// ::= 'declare' FunctionHeader
513bool LLParser::parseDeclare() {
514 assert(Lex.getKind() == lltok::kw_declare)((void)0);
515 Lex.Lex();
516
517 std::vector<std::pair<unsigned, MDNode *>> MDs;
518 while (Lex.getKind() == lltok::MetadataVar) {
519 unsigned MDK;
520 MDNode *N;
521 if (parseMetadataAttachment(MDK, N))
522 return true;
523 MDs.push_back({MDK, N});
524 }
525
526 Function *F;
527 if (parseFunctionHeader(F, false))
528 return true;
529 for (auto &MD : MDs)
530 F->addMetadata(MD.first, *MD.second);
531 return false;
532}
533
534/// toplevelentity
535/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
536bool LLParser::parseDefine() {
537 assert(Lex.getKind() == lltok::kw_define)((void)0);
538 Lex.Lex();
539
540 Function *F;
541 return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) ||
542 parseFunctionBody(*F);
543}
544
545/// parseGlobalType
546/// ::= 'constant'
547/// ::= 'global'
548bool LLParser::parseGlobalType(bool &IsConstant) {
549 if (Lex.getKind() == lltok::kw_constant)
550 IsConstant = true;
551 else if (Lex.getKind() == lltok::kw_global)
552 IsConstant = false;
553 else {
554 IsConstant = false;
555 return tokError("expected 'global' or 'constant'");
556 }
557 Lex.Lex();
558 return false;
559}
560
561bool LLParser::parseOptionalUnnamedAddr(
562 GlobalVariable::UnnamedAddr &UnnamedAddr) {
563 if (EatIfPresent(lltok::kw_unnamed_addr))
564 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
565 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
566 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
567 else
568 UnnamedAddr = GlobalValue::UnnamedAddr::None;
569 return false;
570}
571
572/// parseUnnamedGlobal:
573/// OptionalVisibility (ALIAS | IFUNC) ...
574/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
575/// OptionalDLLStorageClass
576/// ... -> global variable
577/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
578/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
579/// OptionalVisibility
580/// OptionalDLLStorageClass
581/// ... -> global variable
582bool LLParser::parseUnnamedGlobal() {
583 unsigned VarID = NumberedVals.size();
584 std::string Name;
585 LocTy NameLoc = Lex.getLoc();
586
587 // Handle the GlobalID form.
588 if (Lex.getKind() == lltok::GlobalID) {
589 if (Lex.getUIntVal() != VarID)
590 return error(Lex.getLoc(),
591 "variable expected to be numbered '%" + Twine(VarID) + "'");
592 Lex.Lex(); // eat GlobalID;
593
594 if (parseToken(lltok::equal, "expected '=' after name"))
595 return true;
596 }
597
598 bool HasLinkage;
599 unsigned Linkage, Visibility, DLLStorageClass;
600 bool DSOLocal;
601 GlobalVariable::ThreadLocalMode TLM;
602 GlobalVariable::UnnamedAddr UnnamedAddr;
603 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
604 DSOLocal) ||
605 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
606 return true;
607
608 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
609 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
610 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
611
612 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
613 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
614}
615
616/// parseNamedGlobal:
617/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
618/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
619/// OptionalVisibility OptionalDLLStorageClass
620/// ... -> global variable
621bool LLParser::parseNamedGlobal() {
622 assert(Lex.getKind() == lltok::GlobalVar)((void)0);
623 LocTy NameLoc = Lex.getLoc();
624 std::string Name = Lex.getStrVal();
625 Lex.Lex();
626
627 bool HasLinkage;
628 unsigned Linkage, Visibility, DLLStorageClass;
629 bool DSOLocal;
630 GlobalVariable::ThreadLocalMode TLM;
631 GlobalVariable::UnnamedAddr UnnamedAddr;
632 if (parseToken(lltok::equal, "expected '=' in global variable") ||
633 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
634 DSOLocal) ||
635 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
636 return true;
637
638 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
639 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
640 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
641
642 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
643 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
644}
645
646bool LLParser::parseComdat() {
647 assert(Lex.getKind() == lltok::ComdatVar)((void)0);
648 std::string Name = Lex.getStrVal();
649 LocTy NameLoc = Lex.getLoc();
650 Lex.Lex();
651
652 if (parseToken(lltok::equal, "expected '=' here"))
653 return true;
654
655 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
656 return tokError("expected comdat type");
657
658 Comdat::SelectionKind SK;
659 switch (Lex.getKind()) {
660 default:
661 return tokError("unknown selection kind");
662 case lltok::kw_any:
663 SK = Comdat::Any;
664 break;
665 case lltok::kw_exactmatch:
666 SK = Comdat::ExactMatch;
667 break;
668 case lltok::kw_largest:
669 SK = Comdat::Largest;
670 break;
671 case lltok::kw_nodeduplicate:
672 SK = Comdat::NoDeduplicate;
673 break;
674 case lltok::kw_samesize:
675 SK = Comdat::SameSize;
676 break;
677 }
678 Lex.Lex();
679
680 // See if the comdat was forward referenced, if so, use the comdat.
681 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
682 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
683 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
684 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
685
686 Comdat *C;
687 if (I != ComdatSymTab.end())
688 C = &I->second;
689 else
690 C = M->getOrInsertComdat(Name);
691 C->setSelectionKind(SK);
692
693 return false;
694}
695
696// MDString:
697// ::= '!' STRINGCONSTANT
698bool LLParser::parseMDString(MDString *&Result) {
699 std::string Str;
700 if (parseStringConstant(Str))
701 return true;
702 Result = MDString::get(Context, Str);
703 return false;
704}
705
706// MDNode:
707// ::= '!' MDNodeNumber
708bool LLParser::parseMDNodeID(MDNode *&Result) {
709 // !{ ..., !42, ... }
710 LocTy IDLoc = Lex.getLoc();
711 unsigned MID = 0;
712 if (parseUInt32(MID))
713 return true;
714
715 // If not a forward reference, just return it now.
716 if (NumberedMetadata.count(MID)) {
717 Result = NumberedMetadata[MID];
718 return false;
719 }
720
721 // Otherwise, create MDNode forward reference.
722 auto &FwdRef = ForwardRefMDNodes[MID];
723 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
724
725 Result = FwdRef.first.get();
726 NumberedMetadata[MID].reset(Result);
727 return false;
728}
729
730/// parseNamedMetadata:
731/// !foo = !{ !1, !2 }
732bool LLParser::parseNamedMetadata() {
733 assert(Lex.getKind() == lltok::MetadataVar)((void)0);
734 std::string Name = Lex.getStrVal();
735 Lex.Lex();
736
737 if (parseToken(lltok::equal, "expected '=' here") ||
738 parseToken(lltok::exclaim, "Expected '!' here") ||
739 parseToken(lltok::lbrace, "Expected '{' here"))
740 return true;
741
742 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
743 if (Lex.getKind() != lltok::rbrace)
744 do {
745 MDNode *N = nullptr;
746 // parse DIExpressions inline as a special case. They are still MDNodes,
747 // so they can still appear in named metadata. Remove this logic if they
748 // become plain Metadata.
749 if (Lex.getKind() == lltok::MetadataVar &&
750 Lex.getStrVal() == "DIExpression") {
751 if (parseDIExpression(N, /*IsDistinct=*/false))
752 return true;
753 // DIArgLists should only appear inline in a function, as they may
754 // contain LocalAsMetadata arguments which require a function context.
755 } else if (Lex.getKind() == lltok::MetadataVar &&
756 Lex.getStrVal() == "DIArgList") {
757 return tokError("found DIArgList outside of function");
758 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
759 parseMDNodeID(N)) {
760 return true;
761 }
762 NMD->addOperand(N);
763 } while (EatIfPresent(lltok::comma));
764
765 return parseToken(lltok::rbrace, "expected end of metadata node");
766}
767
768/// parseStandaloneMetadata:
769/// !42 = !{...}
770bool LLParser::parseStandaloneMetadata() {
771 assert(Lex.getKind() == lltok::exclaim)((void)0);
772 Lex.Lex();
773 unsigned MetadataID = 0;
774
775 MDNode *Init;
776 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
777 return true;
778
779 // Detect common error, from old metadata syntax.
780 if (Lex.getKind() == lltok::Type)
781 return tokError("unexpected type in metadata definition");
782
783 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
784 if (Lex.getKind() == lltok::MetadataVar) {
785 if (parseSpecializedMDNode(Init, IsDistinct))
786 return true;
787 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
788 parseMDTuple(Init, IsDistinct))
789 return true;
790
791 // See if this was forward referenced, if so, handle it.
792 auto FI = ForwardRefMDNodes.find(MetadataID);
793 if (FI != ForwardRefMDNodes.end()) {
794 FI->second.first->replaceAllUsesWith(Init);
795 ForwardRefMDNodes.erase(FI);
796
797 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work")((void)0);
798 } else {
799 if (NumberedMetadata.count(MetadataID))
800 return tokError("Metadata id is already used");
801 NumberedMetadata[MetadataID].reset(Init);
802 }
803
804 return false;
805}
806
807// Skips a single module summary entry.
808bool LLParser::skipModuleSummaryEntry() {
809 // Each module summary entry consists of a tag for the entry
810 // type, followed by a colon, then the fields which may be surrounded by
811 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
812 // support is in place we will look for the tokens corresponding to the
813 // expected tags.
814 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
815 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
816 Lex.getKind() != lltok::kw_blockcount)
817 return tokError(
818 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
819 "start of summary entry");
820 if (Lex.getKind() == lltok::kw_flags)
821 return parseSummaryIndexFlags();
822 if (Lex.getKind() == lltok::kw_blockcount)
823 return parseBlockCount();
824 Lex.Lex();
825 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
826 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
827 return true;
828 // Now walk through the parenthesized entry, until the number of open
829 // parentheses goes back down to 0 (the first '(' was parsed above).
830 unsigned NumOpenParen = 1;
831 do {
832 switch (Lex.getKind()) {
833 case lltok::lparen:
834 NumOpenParen++;
835 break;
836 case lltok::rparen:
837 NumOpenParen--;
838 break;
839 case lltok::Eof:
840 return tokError("found end of file while parsing summary entry");
841 default:
842 // Skip everything in between parentheses.
843 break;
844 }
845 Lex.Lex();
846 } while (NumOpenParen > 0);
847 return false;
848}
849
850/// SummaryEntry
851/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
852bool LLParser::parseSummaryEntry() {
853 assert(Lex.getKind() == lltok::SummaryID)((void)0);
854 unsigned SummaryID = Lex.getUIntVal();
855
856 // For summary entries, colons should be treated as distinct tokens,
857 // not an indication of the end of a label token.
858 Lex.setIgnoreColonInIdentifiers(true);
859
860 Lex.Lex();
861 if (parseToken(lltok::equal, "expected '=' here"))
862 return true;
863
864 // If we don't have an index object, skip the summary entry.
865 if (!Index)
866 return skipModuleSummaryEntry();
867
868 bool result = false;
869 switch (Lex.getKind()) {
870 case lltok::kw_gv:
871 result = parseGVEntry(SummaryID);
872 break;
873 case lltok::kw_module:
874 result = parseModuleEntry(SummaryID);
875 break;
876 case lltok::kw_typeid:
877 result = parseTypeIdEntry(SummaryID);
878 break;
879 case lltok::kw_typeidCompatibleVTable:
880 result = parseTypeIdCompatibleVtableEntry(SummaryID);
881 break;
882 case lltok::kw_flags:
883 result = parseSummaryIndexFlags();
884 break;
885 case lltok::kw_blockcount:
886 result = parseBlockCount();
887 break;
888 default:
889 result = error(Lex.getLoc(), "unexpected summary kind");
890 break;
891 }
892 Lex.setIgnoreColonInIdentifiers(false);
893 return result;
894}
895
896static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
897 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
898 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
899}
900
901// If there was an explicit dso_local, update GV. In the absence of an explicit
902// dso_local we keep the default value.
903static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
904 if (DSOLocal)
905 GV.setDSOLocal(true);
906}
907
908static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1,
909 Type *Ty2) {
910 std::string ErrString;
911 raw_string_ostream ErrOS(ErrString);
912 ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")";
913 return ErrOS.str();
914}
915
916/// parseIndirectSymbol:
917/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
918/// OptionalVisibility OptionalDLLStorageClass
919/// OptionalThreadLocal OptionalUnnamedAddr
920/// 'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
921///
922/// IndirectSymbol
923/// ::= TypeAndValue
924///
925/// IndirectSymbolAttr
926/// ::= ',' 'partition' StringConstant
927///
928/// Everything through OptionalUnnamedAddr has already been parsed.
929///
930bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
931 unsigned L, unsigned Visibility,
932 unsigned DLLStorageClass, bool DSOLocal,
933 GlobalVariable::ThreadLocalMode TLM,
934 GlobalVariable::UnnamedAddr UnnamedAddr) {
935 bool IsAlias;
936 if (Lex.getKind() == lltok::kw_alias)
937 IsAlias = true;
938 else if (Lex.getKind() == lltok::kw_ifunc)
939 IsAlias = false;
940 else
941 llvm_unreachable("Not an alias or ifunc!")__builtin_unreachable();
942 Lex.Lex();
943
944 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
945
946 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
947 return error(NameLoc, "invalid linkage type for alias");
948
949 if (!isValidVisibilityForLinkage(Visibility, L))
950 return error(NameLoc,
951 "symbol with local linkage must have default visibility");
952
953 Type *Ty;
954 LocTy ExplicitTypeLoc = Lex.getLoc();
955 if (parseType(Ty) ||
956 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
957 return true;
958
959 Constant *Aliasee;
960 LocTy AliaseeLoc = Lex.getLoc();
961 if (Lex.getKind() != lltok::kw_bitcast &&
962 Lex.getKind() != lltok::kw_getelementptr &&
963 Lex.getKind() != lltok::kw_addrspacecast &&
964 Lex.getKind() != lltok::kw_inttoptr) {
965 if (parseGlobalTypeAndValue(Aliasee))
966 return true;
967 } else {
968 // The bitcast dest type is not present, it is implied by the dest type.
969 ValID ID;
970 if (parseValID(ID, /*PFS=*/nullptr))
971 return true;
972 if (ID.Kind != ValID::t_Constant)
973 return error(AliaseeLoc, "invalid aliasee");
974 Aliasee = ID.ConstantVal;
975 }
976
977 Type *AliaseeType = Aliasee->getType();
978 auto *PTy = dyn_cast<PointerType>(AliaseeType);
979 if (!PTy)
980 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
981 unsigned AddrSpace = PTy->getAddressSpace();
982
983 if (IsAlias && !PTy->isOpaqueOrPointeeTypeMatches(Ty)) {
984 return error(
985 ExplicitTypeLoc,
986 typeComparisonErrorMessage(
987 "explicit pointee type doesn't match operand's pointee type", Ty,
988 PTy->getElementType()));
989 }
990
991 if (!IsAlias && !PTy->getElementType()->isFunctionTy()) {
992 return error(ExplicitTypeLoc,
993 "explicit pointee type should be a function type");
994 }
995
996 GlobalValue *GVal = nullptr;
997
998 // See if the alias was forward referenced, if so, prepare to replace the
999 // forward reference.
1000 if (!Name.empty()) {
1001 auto I = ForwardRefVals.find(Name);
1002 if (I != ForwardRefVals.end()) {
1003 GVal = I->second.first;
1004 ForwardRefVals.erase(Name);
1005 } else if (M->getNamedValue(Name)) {
1006 return error(NameLoc, "redefinition of global '@" + Name + "'");
1007 }
1008 } else {
1009 auto I = ForwardRefValIDs.find(NumberedVals.size());
1010 if (I != ForwardRefValIDs.end()) {
1011 GVal = I->second.first;
1012 ForwardRefValIDs.erase(I);
1013 }
1014 }
1015
1016 // Okay, create the alias but do not insert it into the module yet.
1017 std::unique_ptr<GlobalIndirectSymbol> GA;
1018 if (IsAlias)
1019 GA.reset(GlobalAlias::create(Ty, AddrSpace,
1020 (GlobalValue::LinkageTypes)Linkage, Name,
1021 Aliasee, /*Parent*/ nullptr));
1022 else
1023 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
1024 (GlobalValue::LinkageTypes)Linkage, Name,
1025 Aliasee, /*Parent*/ nullptr));
1026 GA->setThreadLocalMode(TLM);
1027 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1028 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1029 GA->setUnnamedAddr(UnnamedAddr);
1030 maybeSetDSOLocal(DSOLocal, *GA);
1031
1032 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1033 // Now parse them if there are any.
1034 while (Lex.getKind() == lltok::comma) {
1035 Lex.Lex();
1036
1037 if (Lex.getKind() == lltok::kw_partition) {
1038 Lex.Lex();
1039 GA->setPartition(Lex.getStrVal());
1040 if (parseToken(lltok::StringConstant, "expected partition string"))
1041 return true;
1042 } else {
1043 return tokError("unknown alias or ifunc property!");
1044 }
1045 }
1046
1047 if (Name.empty())
1048 NumberedVals.push_back(GA.get());
1049
1050 if (GVal) {
1051 // Verify that types agree.
1052 if (GVal->getType() != GA->getType())
1053 return error(
1054 ExplicitTypeLoc,
1055 "forward reference and definition of alias have different types");
1056
1057 // If they agree, just RAUW the old value with the alias and remove the
1058 // forward ref info.
1059 GVal->replaceAllUsesWith(GA.get());
1060 GVal->eraseFromParent();
1061 }
1062
1063 // Insert into the module, we know its name won't collide now.
1064 if (IsAlias)
1065 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
1066 else
1067 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
1068 assert(GA->getName() == Name && "Should not be a name conflict!")((void)0);
1069
1070 // The module owns this now
1071 GA.release();
1072
1073 return false;
1074}
1075
1076/// parseGlobal
1077/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1078/// OptionalVisibility OptionalDLLStorageClass
1079/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1080/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1081/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1082/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1083/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1084/// Const OptionalAttrs
1085///
1086/// Everything up to and including OptionalUnnamedAddr has been parsed
1087/// already.
1088///
1089bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
1090 unsigned Linkage, bool HasLinkage,
1091 unsigned Visibility, unsigned DLLStorageClass,
1092 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1093 GlobalVariable::UnnamedAddr UnnamedAddr) {
1094 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1095 return error(NameLoc,
1096 "symbol with local linkage must have default visibility");
1097
1098 unsigned AddrSpace;
1099 bool IsConstant, IsExternallyInitialized;
1100 LocTy IsExternallyInitializedLoc;
1101 LocTy TyLoc;
1102
1103 Type *Ty = nullptr;
1104 if (parseOptionalAddrSpace(AddrSpace) ||
1105 parseOptionalToken(lltok::kw_externally_initialized,
1106 IsExternallyInitialized,
1107 &IsExternallyInitializedLoc) ||
1108 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1109 return true;
1110
1111 // If the linkage is specified and is external, then no initializer is
1112 // present.
1113 Constant *Init = nullptr;
1114 if (!HasLinkage ||
1115 !GlobalValue::isValidDeclarationLinkage(
1116 (GlobalValue::LinkageTypes)Linkage)) {
1117 if (parseGlobalValue(Ty, Init))
1118 return true;
1119 }
1120
1121 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1122 return error(TyLoc, "invalid type for global variable");
1123
1124 GlobalValue *GVal = nullptr;
1125
1126 // See if the global was forward referenced, if so, use the global.
1127 if (!Name.empty()) {
1128 auto I = ForwardRefVals.find(Name);
1129 if (I != ForwardRefVals.end()) {
1130 GVal = I->second.first;
1131 ForwardRefVals.erase(I);
1132 } else if (M->getNamedValue(Name)) {
1133 return error(NameLoc, "redefinition of global '@" + Name + "'");
1134 }
1135 } else {
1136 auto I = ForwardRefValIDs.find(NumberedVals.size());
1137 if (I != ForwardRefValIDs.end()) {
1138 GVal = I->second.first;
1139 ForwardRefValIDs.erase(I);
1140 }
1141 }
1142
1143 GlobalVariable *GV = new GlobalVariable(
1144 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1145 GlobalVariable::NotThreadLocal, AddrSpace);
1146
1147 if (Name.empty())
1148 NumberedVals.push_back(GV);
1149
1150 // Set the parsed properties on the global.
1151 if (Init)
1152 GV->setInitializer(Init);
1153 GV->setConstant(IsConstant);
1154 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1155 maybeSetDSOLocal(DSOLocal, *GV);
1156 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1157 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1158 GV->setExternallyInitialized(IsExternallyInitialized);
1159 GV->setThreadLocalMode(TLM);
1160 GV->setUnnamedAddr(UnnamedAddr);
1161
1162 if (GVal) {
1163 if (!GVal->getType()->isOpaque() && GVal->getValueType() != Ty)
1164 return error(
1165 TyLoc,
1166 "forward reference and definition of global have different types");
1167
1168 GVal->replaceAllUsesWith(GV);
1169 GVal->eraseFromParent();
1170 }
1171
1172 // parse attributes on the global.
1173 while (Lex.getKind() == lltok::comma) {
1174 Lex.Lex();
1175
1176 if (Lex.getKind() == lltok::kw_section) {
1177 Lex.Lex();
1178 GV->setSection(Lex.getStrVal());
1179 if (parseToken(lltok::StringConstant, "expected global section string"))
1180 return true;
1181 } else if (Lex.getKind() == lltok::kw_partition) {
1182 Lex.Lex();
1183 GV->setPartition(Lex.getStrVal());
1184 if (parseToken(lltok::StringConstant, "expected partition string"))
1185 return true;
1186 } else if (Lex.getKind() == lltok::kw_align) {
1187 MaybeAlign Alignment;
1188 if (parseOptionalAlignment(Alignment))
1189 return true;
1190 GV->setAlignment(Alignment);
1191 } else if (Lex.getKind() == lltok::MetadataVar) {
1192 if (parseGlobalObjectMetadataAttachment(*GV))
1193 return true;
1194 } else {
1195 Comdat *C;
1196 if (parseOptionalComdat(Name, C))
1197 return true;
1198 if (C)
1199 GV->setComdat(C);
1200 else
1201 return tokError("unknown global variable property!");
1202 }
1203 }
1204
1205 AttrBuilder Attrs;
1206 LocTy BuiltinLoc;
1207 std::vector<unsigned> FwdRefAttrGrps;
1208 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1209 return true;
1210 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1211 GV->setAttributes(AttributeSet::get(Context, Attrs));
1212 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1213 }
1214
1215 return false;
1216}
1217
1218/// parseUnnamedAttrGrp
1219/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1220bool LLParser::parseUnnamedAttrGrp() {
1221 assert(Lex.getKind() == lltok::kw_attributes)((void)0);
1222 LocTy AttrGrpLoc = Lex.getLoc();
1223 Lex.Lex();
1224
1225 if (Lex.getKind() != lltok::AttrGrpID)
1226 return tokError("expected attribute group id");
1227
1228 unsigned VarID = Lex.getUIntVal();
1229 std::vector<unsigned> unused;
1230 LocTy BuiltinLoc;
1231 Lex.Lex();
1232
1233 if (parseToken(lltok::equal, "expected '=' here") ||
1234 parseToken(lltok::lbrace, "expected '{' here") ||
1235 parseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1236 BuiltinLoc) ||
1237 parseToken(lltok::rbrace, "expected end of attribute group"))
1238 return true;
1239
1240 if (!NumberedAttrBuilders[VarID].hasAttributes())
1241 return error(AttrGrpLoc, "attribute group has no attributes");
1242
1243 return false;
1244}
1245
1246static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind) {
1247 switch (Kind) {
1248#define GET_ATTR_NAMES
1249#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1250 case lltok::kw_##DISPLAY_NAME: \
1251 return Attribute::ENUM_NAME;
1252#include "llvm/IR/Attributes.inc"
1253 default:
1254 return Attribute::None;
1255 }
1256}
1257
1258bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1259 bool InAttrGroup) {
1260 if (Attribute::isTypeAttrKind(Attr))
1261 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1262
1263 switch (Attr) {
1264 case Attribute::Alignment: {
1265 MaybeAlign Alignment;
1266 if (InAttrGroup) {
1267 uint32_t Value = 0;
1268 Lex.Lex();
1269 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1270 return true;
1271 Alignment = Align(Value);
1272 } else {
1273 if (parseOptionalAlignment(Alignment, true))
1274 return true;
1275 }
1276 B.addAlignmentAttr(Alignment);
1277 return false;
1278 }
1279 case Attribute::StackAlignment: {
1280 unsigned Alignment;
1281 if (InAttrGroup) {
1282 Lex.Lex();
1283 if (parseToken(lltok::equal, "expected '=' here") ||
1284 parseUInt32(Alignment))
1285 return true;
1286 } else {
1287 if (parseOptionalStackAlignment(Alignment))
1288 return true;
1289 }
1290 B.addStackAlignmentAttr(Alignment);
1291 return false;
1292 }
1293 case Attribute::AllocSize: {
1294 unsigned ElemSizeArg;
1295 Optional<unsigned> NumElemsArg;
1296 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1297 return true;
1298 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1299 return false;
1300 }
1301 case Attribute::VScaleRange: {
1302 unsigned MinValue, MaxValue;
1303 if (parseVScaleRangeArguments(MinValue, MaxValue))
1304 return true;
1305 B.addVScaleRangeAttr(MinValue, MaxValue);
1306 return false;
1307 }
1308 case Attribute::Dereferenceable: {
1309 uint64_t Bytes;
1310 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1311 return true;
1312 B.addDereferenceableAttr(Bytes);
1313 return false;
1314 }
1315 case Attribute::DereferenceableOrNull: {
1316 uint64_t Bytes;
1317 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1318 return true;
1319 B.addDereferenceableOrNullAttr(Bytes);
1320 return false;
1321 }
1322 default:
1323 B.addAttribute(Attr);
1324 Lex.Lex();
1325 return false;
1326 }
1327}
1328
1329/// parseFnAttributeValuePairs
1330/// ::= <attr> | <attr> '=' <value>
1331bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1332 std::vector<unsigned> &FwdRefAttrGrps,
1333 bool InAttrGrp, LocTy &BuiltinLoc) {
1334 bool HaveError = false;
1335
1336 B.clear();
1337
1338 while (true) {
1339 lltok::Kind Token = Lex.getKind();
1340 if (Token == lltok::rbrace)
1341 return HaveError; // Finished.
1342
1343 if (Token == lltok::StringConstant) {
1344 if (parseStringAttribute(B))
1345 return true;
1346 continue;
1347 }
1348
1349 if (Token == lltok::AttrGrpID) {
1350 // Allow a function to reference an attribute group:
1351 //
1352 // define void @foo() #1 { ... }
1353 if (InAttrGrp) {
1354 HaveError |= error(
1355 Lex.getLoc(),
1356 "cannot have an attribute group reference in an attribute group");
1357 } else {
1358 // Save the reference to the attribute group. We'll fill it in later.
1359 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1360 }
1361 Lex.Lex();
1362 continue;
1363 }
1364
1365 SMLoc Loc = Lex.getLoc();
1366 if (Token == lltok::kw_builtin)
1367 BuiltinLoc = Loc;
1368
1369 Attribute::AttrKind Attr = tokenToAttribute(Token);
1370 if (Attr == Attribute::None) {
1371 if (!InAttrGrp)
1372 return HaveError;
1373 return error(Lex.getLoc(), "unterminated attribute group");
1374 }
1375
1376 if (parseEnumAttribute(Attr, B, InAttrGrp))
1377 return true;
1378
1379 // As a hack, we allow function alignment to be initially parsed as an
1380 // attribute on a function declaration/definition or added to an attribute
1381 // group and later moved to the alignment field.
1382 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1383 HaveError |= error(Loc, "this attribute does not apply to functions");
1384 }
1385}
1386
1387//===----------------------------------------------------------------------===//
1388// GlobalValue Reference/Resolution Routines.
1389//===----------------------------------------------------------------------===//
1390
1391static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy) {
1392 // For opaque pointers, the used global type does not matter. We will later
1393 // RAUW it with a global/function of the correct type.
1394 if (PTy->isOpaque())
1395 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1396 GlobalValue::ExternalWeakLinkage, nullptr, "",
1397 nullptr, GlobalVariable::NotThreadLocal,
1398 PTy->getAddressSpace());
1399
1400 if (auto *FT = dyn_cast<FunctionType>(PTy->getPointerElementType()))
1401 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1402 PTy->getAddressSpace(), "", M);
1403 else
1404 return new GlobalVariable(*M, PTy->getPointerElementType(), false,
1405 GlobalValue::ExternalWeakLinkage, nullptr, "",
1406 nullptr, GlobalVariable::NotThreadLocal,
1407 PTy->getAddressSpace());
1408}
1409
1410Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1411 Value *Val, bool IsCall) {
1412 Type *ValTy = Val->getType();
1413 if (ValTy == Ty)
1414 return Val;
1415 // For calls, we also allow opaque pointers.
1416 if (IsCall && ValTy == PointerType::get(Ty->getContext(),
1417 Ty->getPointerAddressSpace()))
1418 return Val;
1419 if (Ty->isLabelTy())
1420 error(Loc, "'" + Name + "' is not a basic block");
1421 else
1422 error(Loc, "'" + Name + "' defined with type '" +
1423 getTypeString(Val->getType()) + "' but expected '" +
1424 getTypeString(Ty) + "'");
1425 return nullptr;
1426}
1427
1428/// getGlobalVal - Get a value with the specified name or ID, creating a
1429/// forward reference record if needed. This can return null if the value
1430/// exists but does not have the right type.
1431GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1432 LocTy Loc, bool IsCall) {
1433 PointerType *PTy = dyn_cast<PointerType>(Ty);
1434 if (!PTy) {
1435 error(Loc, "global variable reference must have pointer type");
1436 return nullptr;
1437 }
1438
1439 // Look this name up in the normal function symbol table.
1440 GlobalValue *Val =
1441 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1442
1443 // If this is a forward reference for the value, see if we already created a
1444 // forward ref record.
1445 if (!Val) {
1446 auto I = ForwardRefVals.find(Name);
1447 if (I != ForwardRefVals.end())
1448 Val = I->second.first;
1449 }
1450
1451 // If we have the value in the symbol table or fwd-ref table, return it.
1452 if (Val)
1453 return cast_or_null<GlobalValue>(
1454 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1455
1456 // Otherwise, create a new forward reference for this value and remember it.
1457 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1458 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1459 return FwdVal;
1460}
1461
1462GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1463 bool IsCall) {
1464 PointerType *PTy = dyn_cast<PointerType>(Ty);
1465 if (!PTy) {
1466 error(Loc, "global variable reference must have pointer type");
1467 return nullptr;
1468 }
1469
1470 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1471
1472 // If this is a forward reference for the value, see if we already created a
1473 // forward ref record.
1474 if (!Val) {
1475 auto I = ForwardRefValIDs.find(ID);
1476 if (I != ForwardRefValIDs.end())
1477 Val = I->second.first;
1478 }
1479
1480 // If we have the value in the symbol table or fwd-ref table, return it.
1481 if (Val)
1482 return cast_or_null<GlobalValue>(
1483 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1484
1485 // Otherwise, create a new forward reference for this value and remember it.
1486 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1487 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1488 return FwdVal;
1489}
1490
1491//===----------------------------------------------------------------------===//
1492// Comdat Reference/Resolution Routines.
1493//===----------------------------------------------------------------------===//
1494
1495Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1496 // Look this name up in the comdat symbol table.
1497 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1498 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1499 if (I != ComdatSymTab.end())
1500 return &I->second;
1501
1502 // Otherwise, create a new forward reference for this value and remember it.
1503 Comdat *C = M->getOrInsertComdat(Name);
1504 ForwardRefComdats[Name] = Loc;
1505 return C;
1506}
1507
1508//===----------------------------------------------------------------------===//
1509// Helper Routines.
1510//===----------------------------------------------------------------------===//
1511
1512/// parseToken - If the current token has the specified kind, eat it and return
1513/// success. Otherwise, emit the specified error and return failure.
1514bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1515 if (Lex.getKind() != T)
1516 return tokError(ErrMsg);
1517 Lex.Lex();
1518 return false;
1519}
1520
1521/// parseStringConstant
1522/// ::= StringConstant
1523bool LLParser::parseStringConstant(std::string &Result) {
1524 if (Lex.getKind() != lltok::StringConstant)
1525 return tokError("expected string constant");
1526 Result = Lex.getStrVal();
1527 Lex.Lex();
1528 return false;
1529}
1530
1531/// parseUInt32
1532/// ::= uint32
1533bool LLParser::parseUInt32(uint32_t &Val) {
1534 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1535 return tokError("expected integer");
1536 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1537 if (Val64 != unsigned(Val64))
1538 return tokError("expected 32-bit integer (too large)");
1539 Val = Val64;
1540 Lex.Lex();
1541 return false;
1542}
1543
1544/// parseUInt64
1545/// ::= uint64
1546bool LLParser::parseUInt64(uint64_t &Val) {
1547 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1548 return tokError("expected integer");
1549 Val = Lex.getAPSIntVal().getLimitedValue();
1550 Lex.Lex();
1551 return false;
1552}
1553
1554/// parseTLSModel
1555/// := 'localdynamic'
1556/// := 'initialexec'
1557/// := 'localexec'
1558bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1559 switch (Lex.getKind()) {
1560 default:
1561 return tokError("expected localdynamic, initialexec or localexec");
1562 case lltok::kw_localdynamic:
1563 TLM = GlobalVariable::LocalDynamicTLSModel;
1564 break;
1565 case lltok::kw_initialexec:
1566 TLM = GlobalVariable::InitialExecTLSModel;
1567 break;
1568 case lltok::kw_localexec:
1569 TLM = GlobalVariable::LocalExecTLSModel;
1570 break;
1571 }
1572
1573 Lex.Lex();
1574 return false;
1575}
1576
1577/// parseOptionalThreadLocal
1578/// := /*empty*/
1579/// := 'thread_local'
1580/// := 'thread_local' '(' tlsmodel ')'
1581bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1582 TLM = GlobalVariable::NotThreadLocal;
1583 if (!EatIfPresent(lltok::kw_thread_local))
1584 return false;
1585
1586 TLM = GlobalVariable::GeneralDynamicTLSModel;
1587 if (Lex.getKind() == lltok::lparen) {
1588 Lex.Lex();
1589 return parseTLSModel(TLM) ||
1590 parseToken(lltok::rparen, "expected ')' after thread local model");
1591 }
1592 return false;
1593}
1594
1595/// parseOptionalAddrSpace
1596/// := /*empty*/
1597/// := 'addrspace' '(' uint32 ')'
1598bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1599 AddrSpace = DefaultAS;
1600 if (!EatIfPresent(lltok::kw_addrspace))
1601 return false;
1602 return parseToken(lltok::lparen, "expected '(' in address space") ||
1603 parseUInt32(AddrSpace) ||
1604 parseToken(lltok::rparen, "expected ')' in address space");
1605}
1606
1607/// parseStringAttribute
1608/// := StringConstant
1609/// := StringConstant '=' StringConstant
1610bool LLParser::parseStringAttribute(AttrBuilder &B) {
1611 std::string Attr = Lex.getStrVal();
1612 Lex.Lex();
1613 std::string Val;
1614 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1615 return true;
1616 B.addAttribute(Attr, Val);
1617 return false;
1618}
1619
1620/// Parse a potentially empty list of parameter or return attributes.
1621bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1622 bool HaveError = false;
1623
1624 B.clear();
1625
1626 while (true) {
1627 lltok::Kind Token = Lex.getKind();
1628 if (Token == lltok::StringConstant) {
1629 if (parseStringAttribute(B))
1630 return true;
1631 continue;
1632 }
1633
1634 SMLoc Loc = Lex.getLoc();
1635 Attribute::AttrKind Attr = tokenToAttribute(Token);
1636 if (Attr == Attribute::None)
1637 return HaveError;
1638
1639 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
1640 return true;
1641
1642 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
1643 HaveError |= error(Loc, "this attribute does not apply to parameters");
1644 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
1645 HaveError |= error(Loc, "this attribute does not apply to return values");
1646 }
1647}
1648
1649static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1650 HasLinkage = true;
1651 switch (Kind) {
1652 default:
1653 HasLinkage = false;
1654 return GlobalValue::ExternalLinkage;
1655 case lltok::kw_private:
1656 return GlobalValue::PrivateLinkage;
1657 case lltok::kw_internal:
1658 return GlobalValue::InternalLinkage;
1659 case lltok::kw_weak:
1660 return GlobalValue::WeakAnyLinkage;
1661 case lltok::kw_weak_odr:
1662 return GlobalValue::WeakODRLinkage;
1663 case lltok::kw_linkonce:
1664 return GlobalValue::LinkOnceAnyLinkage;
1665 case lltok::kw_linkonce_odr:
1666 return GlobalValue::LinkOnceODRLinkage;
1667 case lltok::kw_available_externally:
1668 return GlobalValue::AvailableExternallyLinkage;
1669 case lltok::kw_appending:
1670 return GlobalValue::AppendingLinkage;
1671 case lltok::kw_common:
1672 return GlobalValue::CommonLinkage;
1673 case lltok::kw_extern_weak:
1674 return GlobalValue::ExternalWeakLinkage;
1675 case lltok::kw_external:
1676 return GlobalValue::ExternalLinkage;
1677 }
1678}
1679
1680/// parseOptionalLinkage
1681/// ::= /*empty*/
1682/// ::= 'private'
1683/// ::= 'internal'
1684/// ::= 'weak'
1685/// ::= 'weak_odr'
1686/// ::= 'linkonce'
1687/// ::= 'linkonce_odr'
1688/// ::= 'available_externally'
1689/// ::= 'appending'
1690/// ::= 'common'
1691/// ::= 'extern_weak'
1692/// ::= 'external'
1693bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1694 unsigned &Visibility,
1695 unsigned &DLLStorageClass, bool &DSOLocal) {
1696 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1697 if (HasLinkage)
1698 Lex.Lex();
1699 parseOptionalDSOLocal(DSOLocal);
1700 parseOptionalVisibility(Visibility);
1701 parseOptionalDLLStorageClass(DLLStorageClass);
1702
1703 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1704 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1705 }
1706
1707 return false;
1708}
1709
1710void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
1711 switch (Lex.getKind()) {
1712 default:
1713 DSOLocal = false;
1714 break;
1715 case lltok::kw_dso_local:
1716 DSOLocal = true;
1717 Lex.Lex();
1718 break;
1719 case lltok::kw_dso_preemptable:
1720 DSOLocal = false;
1721 Lex.Lex();
1722 break;
1723 }
1724}
1725
1726/// parseOptionalVisibility
1727/// ::= /*empty*/
1728/// ::= 'default'
1729/// ::= 'hidden'
1730/// ::= 'protected'
1731///
1732void LLParser::parseOptionalVisibility(unsigned &Res) {
1733 switch (Lex.getKind()) {
1734 default:
1735 Res = GlobalValue::DefaultVisibility;
1736 return;
1737 case lltok::kw_default:
1738 Res = GlobalValue::DefaultVisibility;
1739 break;
1740 case lltok::kw_hidden:
1741 Res = GlobalValue::HiddenVisibility;
1742 break;
1743 case lltok::kw_protected:
1744 Res = GlobalValue::ProtectedVisibility;
1745 break;
1746 }
1747 Lex.Lex();
1748}
1749
1750/// parseOptionalDLLStorageClass
1751/// ::= /*empty*/
1752/// ::= 'dllimport'
1753/// ::= 'dllexport'
1754///
1755void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
1756 switch (Lex.getKind()) {
1757 default:
1758 Res = GlobalValue::DefaultStorageClass;
1759 return;
1760 case lltok::kw_dllimport:
1761 Res = GlobalValue::DLLImportStorageClass;
1762 break;
1763 case lltok::kw_dllexport:
1764 Res = GlobalValue::DLLExportStorageClass;
1765 break;
1766 }
1767 Lex.Lex();
1768}
1769
1770/// parseOptionalCallingConv
1771/// ::= /*empty*/
1772/// ::= 'ccc'
1773/// ::= 'fastcc'
1774/// ::= 'intel_ocl_bicc'
1775/// ::= 'coldcc'
1776/// ::= 'cfguard_checkcc'
1777/// ::= 'x86_stdcallcc'
1778/// ::= 'x86_fastcallcc'
1779/// ::= 'x86_thiscallcc'
1780/// ::= 'x86_vectorcallcc'
1781/// ::= 'arm_apcscc'
1782/// ::= 'arm_aapcscc'
1783/// ::= 'arm_aapcs_vfpcc'
1784/// ::= 'aarch64_vector_pcs'
1785/// ::= 'aarch64_sve_vector_pcs'
1786/// ::= 'msp430_intrcc'
1787/// ::= 'avr_intrcc'
1788/// ::= 'avr_signalcc'
1789/// ::= 'ptx_kernel'
1790/// ::= 'ptx_device'
1791/// ::= 'spir_func'
1792/// ::= 'spir_kernel'
1793/// ::= 'x86_64_sysvcc'
1794/// ::= 'win64cc'
1795/// ::= 'webkit_jscc'
1796/// ::= 'anyregcc'
1797/// ::= 'preserve_mostcc'
1798/// ::= 'preserve_allcc'
1799/// ::= 'ghccc'
1800/// ::= 'swiftcc'
1801/// ::= 'swifttailcc'
1802/// ::= 'x86_intrcc'
1803/// ::= 'hhvmcc'
1804/// ::= 'hhvm_ccc'
1805/// ::= 'cxx_fast_tlscc'
1806/// ::= 'amdgpu_vs'
1807/// ::= 'amdgpu_ls'
1808/// ::= 'amdgpu_hs'
1809/// ::= 'amdgpu_es'
1810/// ::= 'amdgpu_gs'
1811/// ::= 'amdgpu_ps'
1812/// ::= 'amdgpu_cs'
1813/// ::= 'amdgpu_kernel'
1814/// ::= 'tailcc'
1815/// ::= 'cc' UINT
1816///
1817bool LLParser::parseOptionalCallingConv(unsigned &CC) {
1818 switch (Lex.getKind()) {
1819 default: CC = CallingConv::C; return false;
1820 case lltok::kw_ccc: CC = CallingConv::C; break;
1821 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1822 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1823 case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;
1824 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1825 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1826 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
1827 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1828 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1829 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1830 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1831 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1832 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
1833 case lltok::kw_aarch64_sve_vector_pcs:
1834 CC = CallingConv::AArch64_SVE_VectorCall;
1835 break;
1836 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1837 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1838 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1839 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1840 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1841 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1842 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1843 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1844 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1845 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
1846 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1847 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1848 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1849 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1850 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1851 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1852 case lltok::kw_swifttailcc: CC = CallingConv::SwiftTail; break;
1853 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1854 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1855 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1856 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1857 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1858 case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break;
1859 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
1860 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
1861 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
1862 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1863 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1864 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
1865 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
1866 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
1867 case lltok::kw_cc: {
1868 Lex.Lex();
1869 return parseUInt32(CC);
1870 }
1871 }
1872
1873 Lex.Lex();
1874 return false;
1875}
1876
1877/// parseMetadataAttachment
1878/// ::= !dbg !42
1879bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1880 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment")((void)0);
1881
1882 std::string Name = Lex.getStrVal();
1883 Kind = M->getMDKindID(Name);
1884 Lex.Lex();
1885
1886 return parseMDNode(MD);
1887}
1888
1889/// parseInstructionMetadata
1890/// ::= !dbg !42 (',' !dbg !57)*
1891bool LLParser::parseInstructionMetadata(Instruction &Inst) {
1892 do {
1893 if (Lex.getKind() != lltok::MetadataVar)
1894 return tokError("expected metadata after comma");
1895
1896 unsigned MDK;
1897 MDNode *N;
1898 if (parseMetadataAttachment(MDK, N))
1899 return true;
1900
1901 Inst.setMetadata(MDK, N);
1902 if (MDK == LLVMContext::MD_tbaa)
1903 InstsWithTBAATag.push_back(&Inst);
1904
1905 // If this is the end of the list, we're done.
1906 } while (EatIfPresent(lltok::comma));
1907 return false;
1908}
1909
1910/// parseGlobalObjectMetadataAttachment
1911/// ::= !dbg !57
1912bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1913 unsigned MDK;
1914 MDNode *N;
1915 if (parseMetadataAttachment(MDK, N))
1916 return true;
1917
1918 GO.addMetadata(MDK, *N);
1919 return false;
1920}
1921
1922/// parseOptionalFunctionMetadata
1923/// ::= (!dbg !57)*
1924bool LLParser::parseOptionalFunctionMetadata(Function &F) {
1925 while (Lex.getKind() == lltok::MetadataVar)
1926 if (parseGlobalObjectMetadataAttachment(F))
1927 return true;
1928 return false;
1929}
1930
1931/// parseOptionalAlignment
1932/// ::= /* empty */
1933/// ::= 'align' 4
1934bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
1935 Alignment = None;
1936 if (!EatIfPresent(lltok::kw_align))
1937 return false;
1938 LocTy AlignLoc = Lex.getLoc();
1939 uint32_t Value = 0;
1940
1941 LocTy ParenLoc = Lex.getLoc();
1942 bool HaveParens = false;
1943 if (AllowParens) {
1944 if (EatIfPresent(lltok::lparen))
1945 HaveParens = true;
1946 }
1947
1948 if (parseUInt32(Value))
1949 return true;
1950
1951 if (HaveParens && !EatIfPresent(lltok::rparen))
1952 return error(ParenLoc, "expected ')'");
1953
1954 if (!isPowerOf2_32(Value))
1955 return error(AlignLoc, "alignment is not a power of two");
1956 if (Value > Value::MaximumAlignment)
1957 return error(AlignLoc, "huge alignments are not supported yet");
1958 Alignment = Align(Value);
1959 return false;
1960}
1961
1962/// parseOptionalDerefAttrBytes
1963/// ::= /* empty */
1964/// ::= AttrKind '(' 4 ')'
1965///
1966/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1967bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1968 uint64_t &Bytes) {
1969 assert((AttrKind == lltok::kw_dereferenceable ||((void)0)
1970 AttrKind == lltok::kw_dereferenceable_or_null) &&((void)0)
1971 "contract!")((void)0);
1972
1973 Bytes = 0;
1974 if (!EatIfPresent(AttrKind))
1975 return false;
1976 LocTy ParenLoc = Lex.getLoc();
1977 if (!EatIfPresent(lltok::lparen))
1978 return error(ParenLoc, "expected '('");
1979 LocTy DerefLoc = Lex.getLoc();
1980 if (parseUInt64(Bytes))
1981 return true;
1982 ParenLoc = Lex.getLoc();
1983 if (!EatIfPresent(lltok::rparen))
1984 return error(ParenLoc, "expected ')'");
1985 if (!Bytes)
1986 return error(DerefLoc, "dereferenceable bytes must be non-zero");
1987 return false;
1988}
1989
1990/// parseOptionalCommaAlign
1991/// ::=
1992/// ::= ',' align 4
1993///
1994/// This returns with AteExtraComma set to true if it ate an excess comma at the
1995/// end.
1996bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
1997 bool &AteExtraComma) {
1998 AteExtraComma = false;
1999 while (EatIfPresent(lltok::comma)) {
2000 // Metadata at the end is an early exit.
2001 if (Lex.getKind() == lltok::MetadataVar) {
2002 AteExtraComma = true;
2003 return false;
2004 }
2005
2006 if (Lex.getKind() != lltok::kw_align)
2007 return error(Lex.getLoc(), "expected metadata or 'align'");
2008
2009 if (parseOptionalAlignment(Alignment))
2010 return true;
2011 }
2012
2013 return false;
2014}
2015
2016/// parseOptionalCommaAddrSpace
2017/// ::=
2018/// ::= ',' addrspace(1)
2019///
2020/// This returns with AteExtraComma set to true if it ate an excess comma at the
2021/// end.
2022bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2023 bool &AteExtraComma) {
2024 AteExtraComma = false;
2025 while (EatIfPresent(lltok::comma)) {
2026 // Metadata at the end is an early exit.
2027 if (Lex.getKind() == lltok::MetadataVar) {
2028 AteExtraComma = true;
2029 return false;
2030 }
2031
2032 Loc = Lex.getLoc();
2033 if (Lex.getKind() != lltok::kw_addrspace)
2034 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2035
2036 if (parseOptionalAddrSpace(AddrSpace))
2037 return true;
2038 }
2039
2040 return false;
2041}
2042
2043bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2044 Optional<unsigned> &HowManyArg) {
2045 Lex.Lex();
2046
2047 auto StartParen = Lex.getLoc();
2048 if (!EatIfPresent(lltok::lparen))
2049 return error(StartParen, "expected '('");
2050
2051 if (parseUInt32(BaseSizeArg))
2052 return true;
2053
2054 if (EatIfPresent(lltok::comma)) {
2055 auto HowManyAt = Lex.getLoc();
2056 unsigned HowMany;
2057 if (parseUInt32(HowMany))
2058 return true;
2059 if (HowMany == BaseSizeArg)
2060 return error(HowManyAt,
2061 "'allocsize' indices can't refer to the same parameter");
2062 HowManyArg = HowMany;
2063 } else
2064 HowManyArg = None;
2065
2066 auto EndParen = Lex.getLoc();
2067 if (!EatIfPresent(lltok::rparen))
2068 return error(EndParen, "expected ')'");
2069 return false;
2070}
2071
2072bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2073 unsigned &MaxValue) {
2074 Lex.Lex();
2075
2076 auto StartParen = Lex.getLoc();
2077 if (!EatIfPresent(lltok::lparen))
2078 return error(StartParen, "expected '('");
2079
2080 if (parseUInt32(MinValue))
2081 return true;
2082
2083 if (EatIfPresent(lltok::comma)) {
2084 if (parseUInt32(MaxValue))
2085 return true;
2086 } else
2087 MaxValue = MinValue;
2088
2089 auto EndParen = Lex.getLoc();
2090 if (!EatIfPresent(lltok::rparen))
2091 return error(EndParen, "expected ')'");
2092 return false;
2093}
2094
2095/// parseScopeAndOrdering
2096/// if isAtomic: ::= SyncScope? AtomicOrdering
2097/// else: ::=
2098///
2099/// This sets Scope and Ordering to the parsed values.
2100bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2101 AtomicOrdering &Ordering) {
2102 if (!IsAtomic)
2103 return false;
2104
2105 return parseScope(SSID) || parseOrdering(Ordering);
2106}
2107
2108/// parseScope
2109/// ::= syncscope("singlethread" | "<target scope>")?
2110///
2111/// This sets synchronization scope ID to the ID of the parsed value.
2112bool LLParser::parseScope(SyncScope::ID &SSID) {
2113 SSID = SyncScope::System;
2114 if (EatIfPresent(lltok::kw_syncscope)) {
2115 auto StartParenAt = Lex.getLoc();
2116 if (!EatIfPresent(lltok::lparen))
2117 return error(StartParenAt, "Expected '(' in syncscope");
2118
2119 std::string SSN;
2120 auto SSNAt = Lex.getLoc();
2121 if (parseStringConstant(SSN))
2122 return error(SSNAt, "Expected synchronization scope name");
2123
2124 auto EndParenAt = Lex.getLoc();
2125 if (!EatIfPresent(lltok::rparen))
2126 return error(EndParenAt, "Expected ')' in syncscope");
2127
2128 SSID = Context.getOrInsertSyncScopeID(SSN);
2129 }
2130
2131 return false;
2132}
2133
2134/// parseOrdering
2135/// ::= AtomicOrdering
2136///
2137/// This sets Ordering to the parsed value.
2138bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2139 switch (Lex.getKind()) {
2140 default:
2141 return tokError("Expected ordering on atomic instruction");
2142 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2143 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2144 // Not specified yet:
2145 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2146 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2147 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2148 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2149 case lltok::kw_seq_cst:
2150 Ordering = AtomicOrdering::SequentiallyConsistent;
2151 break;
2152 }
2153 Lex.Lex();
2154 return false;
2155}
2156
2157/// parseOptionalStackAlignment
2158/// ::= /* empty */
2159/// ::= 'alignstack' '(' 4 ')'
2160bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2161 Alignment = 0;
2162 if (!EatIfPresent(lltok::kw_alignstack))
2163 return false;
2164 LocTy ParenLoc = Lex.getLoc();
2165 if (!EatIfPresent(lltok::lparen))
2166 return error(ParenLoc, "expected '('");
2167 LocTy AlignLoc = Lex.getLoc();
2168 if (parseUInt32(Alignment))
2169 return true;
2170 ParenLoc = Lex.getLoc();
2171 if (!EatIfPresent(lltok::rparen))
2172 return error(ParenLoc, "expected ')'");
2173 if (!isPowerOf2_32(Alignment))
2174 return error(AlignLoc, "stack alignment is not a power of two");
2175 return false;
2176}
2177
2178/// parseIndexList - This parses the index list for an insert/extractvalue
2179/// instruction. This sets AteExtraComma in the case where we eat an extra
2180/// comma at the end of the line and find that it is followed by metadata.
2181/// Clients that don't allow metadata can call the version of this function that
2182/// only takes one argument.
2183///
2184/// parseIndexList
2185/// ::= (',' uint32)+
2186///
2187bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2188 bool &AteExtraComma) {
2189 AteExtraComma = false;
2190
2191 if (Lex.getKind() != lltok::comma)
2192 return tokError("expected ',' as start of index list");
2193
2194 while (EatIfPresent(lltok::comma)) {
2195 if (Lex.getKind() == lltok::MetadataVar) {
2196 if (Indices.empty())
2197 return tokError("expected index");
2198 AteExtraComma = true;
2199 return false;
2200 }
2201 unsigned Idx = 0;
2202 if (parseUInt32(Idx))
2203 return true;
2204 Indices.push_back(Idx);
2205 }
2206
2207 return false;
2208}
2209
2210//===----------------------------------------------------------------------===//
2211// Type Parsing.
2212//===----------------------------------------------------------------------===//
2213
2214/// parseType - parse a type.
2215bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2216 SMLoc TypeLoc = Lex.getLoc();
2217 switch (Lex.getKind()) {
2218 default:
2219 return tokError(Msg);
2220 case lltok::Type:
2221 // Type ::= 'float' | 'void' (etc)
2222 Result = Lex.getTyVal();
2223 Lex.Lex();
2224 break;
2225 case lltok::lbrace:
2226 // Type ::= StructType
2227 if (parseAnonStructType(Result, false))
2228 return true;
2229 break;
2230 case lltok::lsquare:
2231 // Type ::= '[' ... ']'
2232 Lex.Lex(); // eat the lsquare.
2233 if (parseArrayVectorType(Result, false))
2234 return true;
2235 break;
2236 case lltok::less: // Either vector or packed struct.
2237 // Type ::= '<' ... '>'
2238 Lex.Lex();
2239 if (Lex.getKind() == lltok::lbrace) {
2240 if (parseAnonStructType(Result, true) ||
2241 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2242 return true;
2243 } else if (parseArrayVectorType(Result, true))
2244 return true;
2245 break;
2246 case lltok::LocalVar: {
2247 // Type ::= %foo
2248 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2249
2250 // If the type hasn't been defined yet, create a forward definition and
2251 // remember where that forward def'n was seen (in case it never is defined).
2252 if (!Entry.first) {
2253 Entry.first = StructType::create(Context, Lex.getStrVal());
2254 Entry.second = Lex.getLoc();
2255 }
2256 Result = Entry.first;
2257 Lex.Lex();
2258 break;
2259 }
2260
2261 case lltok::LocalVarID: {
2262 // Type ::= %4
2263 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2264
2265 // If the type hasn't been defined yet, create a forward definition and
2266 // remember where that forward def'n was seen (in case it never is defined).
2267 if (!Entry.first) {
2268 Entry.first = StructType::create(Context);
2269 Entry.second = Lex.getLoc();
2270 }
2271 Result = Entry.first;
2272 Lex.Lex();
2273 break;
2274 }
2275 }
2276
2277 // Handle (explicit) opaque pointer types (not --force-opaque-pointers).
2278 //
2279 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2280 if (Result->isOpaquePointerTy()) {
2281 unsigned AddrSpace;
2282 if (parseOptionalAddrSpace(AddrSpace))
2283 return true;
2284 Result = PointerType::get(getContext(), AddrSpace);
2285
2286 // Give a nice error for 'ptr*'.
2287 if (Lex.getKind() == lltok::star)
2288 return tokError("ptr* is invalid - use ptr instead");
2289
2290 // Fall through to parsing the type suffixes only if this 'ptr' is a
2291 // function return. Otherwise, return success, implicitly rejecting other
2292 // suffixes.
2293 if (Lex.getKind() != lltok::lparen)
2294 return false;
2295 }
2296
2297 // parse the type suffixes.
2298 while (true) {
2299 switch (Lex.getKind()) {
2300 // End of type.
2301 default:
2302 if (!AllowVoid && Result->isVoidTy())
2303 return error(TypeLoc, "void type only allowed for function results");
2304 return false;
2305
2306 // Type ::= Type '*'
2307 case lltok::star:
2308 if (Result->isLabelTy())
2309 return tokError("basic block pointers are invalid");
2310 if (Result->isVoidTy())
2311 return tokError("pointers to void are invalid - use i8* instead");
2312 if (!PointerType::isValidElementType(Result))
2313 return tokError("pointer to this type is invalid");
2314 Result = PointerType::getUnqual(Result);
2315 Lex.Lex();
2316 break;
2317
2318 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2319 case lltok::kw_addrspace: {
2320 if (Result->isLabelTy())
2321 return tokError("basic block pointers are invalid");
2322 if (Result->isVoidTy())
2323 return tokError("pointers to void are invalid; use i8* instead");
2324 if (!PointerType::isValidElementType(Result))
2325 return tokError("pointer to this type is invalid");
2326 unsigned AddrSpace;
2327 if (parseOptionalAddrSpace(AddrSpace) ||
2328 parseToken(lltok::star, "expected '*' in address space"))
2329 return true;
2330
2331 Result = PointerType::get(Result, AddrSpace);
2332 break;
2333 }
2334
2335 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2336 case lltok::lparen:
2337 if (parseFunctionType(Result))
2338 return true;
2339 break;
2340 }
2341 }
2342}
2343
2344/// parseParameterList
2345/// ::= '(' ')'
2346/// ::= '(' Arg (',' Arg)* ')'
2347/// Arg
2348/// ::= Type OptionalAttributes Value OptionalAttributes
2349bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2350 PerFunctionState &PFS, bool IsMustTailCall,
2351 bool InVarArgsFunc) {
2352 if (parseToken(lltok::lparen, "expected '(' in call"))
2353 return true;
2354
2355 while (Lex.getKind() != lltok::rparen) {
2356 // If this isn't the first argument, we need a comma.
2357 if (!ArgList.empty() &&
2358 parseToken(lltok::comma, "expected ',' in argument list"))
2359 return true;
2360
2361 // parse an ellipsis if this is a musttail call in a variadic function.
2362 if (Lex.getKind() == lltok::dotdotdot) {
2363 const char *Msg = "unexpected ellipsis in argument list for ";
2364 if (!IsMustTailCall)
2365 return tokError(Twine(Msg) + "non-musttail call");
2366 if (!InVarArgsFunc)
2367 return tokError(Twine(Msg) + "musttail call in non-varargs function");
2368 Lex.Lex(); // Lex the '...', it is purely for readability.
2369 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2370 }
2371
2372 // parse the argument.
2373 LocTy ArgLoc;
2374 Type *ArgTy = nullptr;
2375 AttrBuilder ArgAttrs;
2376 Value *V;
2377 if (parseType(ArgTy, ArgLoc))
2378 return true;
2379
2380 if (ArgTy->isMetadataTy()) {
2381 if (parseMetadataAsValue(V, PFS))
2382 return true;
2383 } else {
2384 // Otherwise, handle normal operands.
2385 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2386 return true;
2387 }
2388 ArgList.push_back(ParamInfo(
2389 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2390 }
2391
2392 if (IsMustTailCall && InVarArgsFunc)
2393 return tokError("expected '...' at end of argument list for musttail call "
2394 "in varargs function");
2395
2396 Lex.Lex(); // Lex the ')'.
2397 return false;
2398}
2399
2400/// parseRequiredTypeAttr
2401/// ::= attrname(<ty>)
2402bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
2403 Attribute::AttrKind AttrKind) {
2404 Type *Ty = nullptr;
2405 if (!EatIfPresent(AttrToken))
2406 return true;
2407 if (!EatIfPresent(lltok::lparen))
2408 return error(Lex.getLoc(), "expected '('");
2409 if (parseType(Ty))
2410 return true;
2411 if (!EatIfPresent(lltok::rparen))
2412 return error(Lex.getLoc(), "expected ')'");
2413
2414 B.addTypeAttr(AttrKind, Ty);
2415 return false;
2416}
2417
2418/// parseOptionalOperandBundles
2419/// ::= /*empty*/
2420/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2421///
2422/// OperandBundle
2423/// ::= bundle-tag '(' ')'
2424/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2425///
2426/// bundle-tag ::= String Constant
2427bool LLParser::parseOptionalOperandBundles(
2428 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2429 LocTy BeginLoc = Lex.getLoc();
2430 if (!EatIfPresent(lltok::lsquare))
2431 return false;
2432
2433 while (Lex.getKind() != lltok::rsquare) {
2434 // If this isn't the first operand bundle, we need a comma.
2435 if (!BundleList.empty() &&
2436 parseToken(lltok::comma, "expected ',' in input list"))
2437 return true;
2438
2439 std::string Tag;
2440 if (parseStringConstant(Tag))
2441 return true;
2442
2443 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
2444 return true;
2445
2446 std::vector<Value *> Inputs;
2447 while (Lex.getKind() != lltok::rparen) {
2448 // If this isn't the first input, we need a comma.
2449 if (!Inputs.empty() &&
2450 parseToken(lltok::comma, "expected ',' in input list"))
2451 return true;
2452
2453 Type *Ty = nullptr;
2454 Value *Input = nullptr;
2455 if (parseType(Ty) || parseValue(Ty, Input, PFS))
2456 return true;
2457 Inputs.push_back(Input);
2458 }
2459
2460 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2461
2462 Lex.Lex(); // Lex the ')'.
2463 }
2464
2465 if (BundleList.empty())
2466 return error(BeginLoc, "operand bundle set must not be empty");
2467
2468 Lex.Lex(); // Lex the ']'.
2469 return false;
2470}
2471
2472/// parseArgumentList - parse the argument list for a function type or function
2473/// prototype.
2474/// ::= '(' ArgTypeListI ')'
2475/// ArgTypeListI
2476/// ::= /*empty*/
2477/// ::= '...'
2478/// ::= ArgTypeList ',' '...'
2479/// ::= ArgType (',' ArgType)*
2480///
2481bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2482 bool &IsVarArg) {
2483 unsigned CurValID = 0;
2484 IsVarArg = false;
2485 assert(Lex.getKind() == lltok::lparen)((void)0);
2486 Lex.Lex(); // eat the (.
2487
2488 if (Lex.getKind() == lltok::rparen) {
2489 // empty
2490 } else if (Lex.getKind() == lltok::dotdotdot) {
2491 IsVarArg = true;
2492 Lex.Lex();
2493 } else {
2494 LocTy TypeLoc = Lex.getLoc();
2495 Type *ArgTy = nullptr;
2496 AttrBuilder Attrs;
2497 std::string Name;
2498
2499 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2500 return true;
2501
2502 if (ArgTy->isVoidTy())
2503 return error(TypeLoc, "argument can not have void type");
2504
2505 if (Lex.getKind() == lltok::LocalVar) {
2506 Name = Lex.getStrVal();
2507 Lex.Lex();
2508 } else if (Lex.getKind() == lltok::LocalVarID) {
2509 if (Lex.getUIntVal() != CurValID)
2510 return error(TypeLoc, "argument expected to be numbered '%" +
2511 Twine(CurValID) + "'");
2512 ++CurValID;
2513 Lex.Lex();
2514 }
2515
2516 if (!FunctionType::isValidArgumentType(ArgTy))
2517 return error(TypeLoc, "invalid type for function argument");
2518
2519 ArgList.emplace_back(TypeLoc, ArgTy,
2520 AttributeSet::get(ArgTy->getContext(), Attrs),
2521 std::move(Name));
2522
2523 while (EatIfPresent(lltok::comma)) {
2524 // Handle ... at end of arg list.
2525 if (EatIfPresent(lltok::dotdotdot)) {
2526 IsVarArg = true;
2527 break;
2528 }
2529
2530 // Otherwise must be an argument type.
2531 TypeLoc = Lex.getLoc();
2532 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2533 return true;
2534
2535 if (ArgTy->isVoidTy())
2536 return error(TypeLoc, "argument can not have void type");
2537
2538 if (Lex.getKind() == lltok::LocalVar) {
2539 Name = Lex.getStrVal();
2540 Lex.Lex();
2541 } else {
2542 if (Lex.getKind() == lltok::LocalVarID) {
2543 if (Lex.getUIntVal() != CurValID)
2544 return error(TypeLoc, "argument expected to be numbered '%" +
2545 Twine(CurValID) + "'");
2546 Lex.Lex();
2547 }
2548 ++CurValID;
2549 Name = "";
2550 }
2551
2552 if (!ArgTy->isFirstClassType())
2553 return error(TypeLoc, "invalid type for function argument");
2554
2555 ArgList.emplace_back(TypeLoc, ArgTy,
2556 AttributeSet::get(ArgTy->getContext(), Attrs),
2557 std::move(Name));
2558 }
2559 }
2560
2561 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2562}
2563
2564/// parseFunctionType
2565/// ::= Type ArgumentList OptionalAttrs
2566bool LLParser::parseFunctionType(Type *&Result) {
2567 assert(Lex.getKind() == lltok::lparen)((void)0);
2568
2569 if (!FunctionType::isValidReturnType(Result))
2570 return tokError("invalid function return type");
2571
2572 SmallVector<ArgInfo, 8> ArgList;
2573 bool IsVarArg;
2574 if (parseArgumentList(ArgList, IsVarArg))
2575 return true;
2576
2577 // Reject names on the arguments lists.
2578 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2579 if (!ArgList[i].Name.empty())
2580 return error(ArgList[i].Loc, "argument name invalid in function type");
2581 if (ArgList[i].Attrs.hasAttributes())
2582 return error(ArgList[i].Loc,
2583 "argument attributes invalid in function type");
2584 }
2585
2586 SmallVector<Type*, 16> ArgListTy;
2587 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2588 ArgListTy.push_back(ArgList[i].Ty);
2589
2590 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
2591 return false;
2592}
2593
2594/// parseAnonStructType - parse an anonymous struct type, which is inlined into
2595/// other structs.
2596bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
2597 SmallVector<Type*, 8> Elts;
2598 if (parseStructBody(Elts))
2599 return true;
2600
2601 Result = StructType::get(Context, Elts, Packed);
2602 return false;
2603}
2604
2605/// parseStructDefinition - parse a struct in a 'type' definition.
2606bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
2607 std::pair<Type *, LocTy> &Entry,
2608 Type *&ResultTy) {
2609 // If the type was already defined, diagnose the redefinition.
2610 if (Entry.first && !Entry.second.isValid())
2611 return error(TypeLoc, "redefinition of type");
2612
2613 // If we have opaque, just return without filling in the definition for the
2614 // struct. This counts as a definition as far as the .ll file goes.
2615 if (EatIfPresent(lltok::kw_opaque)) {
2616 // This type is being defined, so clear the location to indicate this.
2617 Entry.second = SMLoc();
2618
2619 // If this type number has never been uttered, create it.
2620 if (!Entry.first)
2621 Entry.first = StructType::create(Context, Name);
2622 ResultTy = Entry.first;
2623 return false;
2624 }
2625
2626 // If the type starts with '<', then it is either a packed struct or a vector.
2627 bool isPacked = EatIfPresent(lltok::less);
2628
2629 // If we don't have a struct, then we have a random type alias, which we
2630 // accept for compatibility with old files. These types are not allowed to be
2631 // forward referenced and not allowed to be recursive.
2632 if (Lex.getKind() != lltok::lbrace) {
2633 if (Entry.first)
2634 return error(TypeLoc, "forward references to non-struct type");
2635
2636 ResultTy = nullptr;
2637 if (isPacked)
2638 return parseArrayVectorType(ResultTy, true);
2639 return parseType(ResultTy);
2640 }
2641
2642 // This type is being defined, so clear the location to indicate this.
2643 Entry.second = SMLoc();
2644
2645 // If this type number has never been uttered, create it.
2646 if (!Entry.first)
2647 Entry.first = StructType::create(Context, Name);
2648
2649 StructType *STy = cast<StructType>(Entry.first);
2650
2651 SmallVector<Type*, 8> Body;
2652 if (parseStructBody(Body) ||
2653 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
2654 return true;
2655
2656 STy->setBody(Body, isPacked);
2657 ResultTy = STy;
2658 return false;
2659}
2660
2661/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2662/// StructType
2663/// ::= '{' '}'
2664/// ::= '{' Type (',' Type)* '}'
2665/// ::= '<' '{' '}' '>'
2666/// ::= '<' '{' Type (',' Type)* '}' '>'
2667bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
2668 assert(Lex.getKind() == lltok::lbrace)((void)0);
2669 Lex.Lex(); // Consume the '{'
2670
2671 // Handle the empty struct.
2672 if (EatIfPresent(lltok::rbrace))
2673 return false;
2674
2675 LocTy EltTyLoc = Lex.getLoc();
2676 Type *Ty = nullptr;
2677 if (parseType(Ty))
2678 return true;
2679 Body.push_back(Ty);
2680
2681 if (!StructType::isValidElementType(Ty))
2682 return error(EltTyLoc, "invalid element type for struct");
2683
2684 while (EatIfPresent(lltok::comma)) {
2685 EltTyLoc = Lex.getLoc();
2686 if (parseType(Ty))
2687 return true;
2688
2689 if (!StructType::isValidElementType(Ty))
2690 return error(EltTyLoc, "invalid element type for struct");
2691
2692 Body.push_back(Ty);
2693 }
2694
2695 return parseToken(lltok::rbrace, "expected '}' at end of struct");
2696}
2697
2698/// parseArrayVectorType - parse an array or vector type, assuming the first
2699/// token has already been consumed.
2700/// Type
2701/// ::= '[' APSINTVAL 'x' Types ']'
2702/// ::= '<' APSINTVAL 'x' Types '>'
2703/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
2704bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
2705 bool Scalable = false;
2706
2707 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
2708 Lex.Lex(); // consume the 'vscale'
2709 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
2710 return true;
2711
2712 Scalable = true;
2713 }
2714
2715 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2716 Lex.getAPSIntVal().getBitWidth() > 64)
2717 return tokError("expected number in address space");
2718
2719 LocTy SizeLoc = Lex.getLoc();
2720 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2721 Lex.Lex();
2722
2723 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
2724 return true;
2725
2726 LocTy TypeLoc = Lex.getLoc();
2727 Type *EltTy = nullptr;
2728 if (parseType(EltTy))
2729 return true;
2730
2731 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
2732 "expected end of sequential type"))
2733 return true;
2734
2735 if (IsVector) {
2736 if (Size == 0)
2737 return error(SizeLoc, "zero element vector is illegal");
2738 if ((unsigned)Size != Size)
2739 return error(SizeLoc, "size too large for vector");
2740 if (!VectorType::isValidElementType(EltTy))
2741 return error(TypeLoc, "invalid vector element type");
2742 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
2743 } else {
2744 if (!ArrayType::isValidElementType(EltTy))
2745 return error(TypeLoc, "invalid array element type");
2746 Result = ArrayType::get(EltTy, Size);
2747 }
2748 return false;
2749}
2750
2751//===----------------------------------------------------------------------===//
2752// Function Semantic Analysis.
2753//===----------------------------------------------------------------------===//
2754
2755LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2756 int functionNumber)
2757 : P(p), F(f), FunctionNumber(functionNumber) {
2758
2759 // Insert unnamed arguments into the NumberedVals list.
2760 for (Argument &A : F.args())
2761 if (!A.hasName())
2762 NumberedVals.push_back(&A);
2763}
2764
2765LLParser::PerFunctionState::~PerFunctionState() {
2766 // If there were any forward referenced non-basicblock values, delete them.
2767
2768 for (const auto &P : ForwardRefVals) {
2769 if (isa<BasicBlock>(P.second.first))
2770 continue;
2771 P.second.first->replaceAllUsesWith(
2772 UndefValue::get(P.second.first->getType()));
2773 P.second.first->deleteValue();
2774 }
2775
2776 for (const auto &P : ForwardRefValIDs) {
2777 if (isa<BasicBlock>(P.second.first))
2778 continue;
2779 P.second.first->replaceAllUsesWith(
2780 UndefValue::get(P.second.first->getType()));
2781 P.second.first->deleteValue();
2782 }
2783}
2784
2785bool LLParser::PerFunctionState::finishFunction() {
2786 if (!ForwardRefVals.empty())
2787 return P.error(ForwardRefVals.begin()->second.second,
2788 "use of undefined value '%" + ForwardRefVals.begin()->first +
2789 "'");
2790 if (!ForwardRefValIDs.empty())
2791 return P.error(ForwardRefValIDs.begin()->second.second,
2792 "use of undefined value '%" +
2793 Twine(ForwardRefValIDs.begin()->first) + "'");
2794 return false;
2795}
2796
2797/// getVal - Get a value with the specified name or ID, creating a
2798/// forward reference record if needed. This can return null if the value
2799/// exists but does not have the right type.
2800Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
2801 LocTy Loc, bool IsCall) {
2802 // Look this name up in the normal function symbol table.
2803 Value *Val = F.getValueSymbolTable()->lookup(Name);
2804
2805 // If this is a forward reference for the value, see if we already created a
2806 // forward ref record.
2807 if (!Val) {
2808 auto I = ForwardRefVals.find(Name);
2809 if (I != ForwardRefVals.end())
2810 Val = I->second.first;
2811 }
2812
2813 // If we have the value in the symbol table or fwd-ref table, return it.
2814 if (Val)
2815 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
2816
2817 // Don't make placeholders with invalid type.
2818 if (!Ty->isFirstClassType()) {
2819 P.error(Loc, "invalid use of a non-first-class type");
2820 return nullptr;
2821 }
2822
2823 // Otherwise, create a new forward reference for this value and remember it.
2824 Value *FwdVal;
2825 if (Ty->isLabelTy()) {
2826 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2827 } else {
2828 FwdVal = new Argument(Ty, Name);
2829 }
2830
2831 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2832 return FwdVal;
2833}
2834
2835Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc,
2836 bool IsCall) {
2837 // Look this name up in the normal function symbol table.
2838 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2839
2840 // If this is a forward reference for the value, see if we already created a
2841 // forward ref record.
2842 if (!Val) {
2843 auto I = ForwardRefValIDs.find(ID);
2844 if (I != ForwardRefValIDs.end())
2845 Val = I->second.first;
2846 }
2847
2848 // If we have the value in the symbol table or fwd-ref table, return it.
2849 if (Val)
2850 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
2851
2852 if (!Ty->isFirstClassType()) {
2853 P.error(Loc, "invalid use of a non-first-class type");
2854 return nullptr;
2855 }
2856
2857 // Otherwise, create a new forward reference for this value and remember it.
2858 Value *FwdVal;
2859 if (Ty->isLabelTy()) {
2860 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2861 } else {
2862 FwdVal = new Argument(Ty);
2863 }
2864
2865 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2866 return FwdVal;
2867}
2868
2869/// setInstName - After an instruction is parsed and inserted into its
2870/// basic block, this installs its name.
2871bool LLParser::PerFunctionState::setInstName(int NameID,
2872 const std::string &NameStr,
2873 LocTy NameLoc, Instruction *Inst) {
2874 // If this instruction has void type, it cannot have a name or ID specified.
2875 if (Inst->getType()->isVoidTy()) {
2876 if (NameID != -1 || !NameStr.empty())
2877 return P.error(NameLoc, "instructions returning void cannot have a name");
2878 return false;
2879 }
2880
2881 // If this was a numbered instruction, verify that the instruction is the
2882 // expected value and resolve any forward references.
2883 if (NameStr.empty()) {
2884 // If neither a name nor an ID was specified, just use the next ID.
2885 if (NameID == -1)
2886 NameID = NumberedVals.size();
2887
2888 if (unsigned(NameID) != NumberedVals.size())
2889 return P.error(NameLoc, "instruction expected to be numbered '%" +
2890 Twine(NumberedVals.size()) + "'");
2891
2892 auto FI = ForwardRefValIDs.find(NameID);
2893 if (FI != ForwardRefValIDs.end()) {
2894 Value *Sentinel = FI->second.first;
2895 if (Sentinel->getType() != Inst->getType())
2896 return P.error(NameLoc, "instruction forward referenced with type '" +
2897 getTypeString(FI->second.first->getType()) +
2898 "'");
2899
2900 Sentinel->replaceAllUsesWith(Inst);
2901 Sentinel->deleteValue();
2902 ForwardRefValIDs.erase(FI);
2903 }
2904
2905 NumberedVals.push_back(Inst);
2906 return false;
2907 }
2908
2909 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2910 auto FI = ForwardRefVals.find(NameStr);
2911 if (FI != ForwardRefVals.end()) {
2912 Value *Sentinel = FI->second.first;
2913 if (Sentinel->getType() != Inst->getType())
2914 return P.error(NameLoc, "instruction forward referenced with type '" +
2915 getTypeString(FI->second.first->getType()) +
2916 "'");
2917
2918 Sentinel->replaceAllUsesWith(Inst);
2919 Sentinel->deleteValue();
2920 ForwardRefVals.erase(FI);
2921 }
2922
2923 // Set the name on the instruction.
2924 Inst->setName(NameStr);
2925
2926 if (Inst->getName() != NameStr)
2927 return P.error(NameLoc, "multiple definition of local value named '" +
2928 NameStr + "'");
2929 return false;
2930}
2931
2932/// getBB - Get a basic block with the specified name or ID, creating a
2933/// forward reference record if needed.
2934BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
2935 LocTy Loc) {
2936 return dyn_cast_or_null<BasicBlock>(
2937 getVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2938}
2939
2940BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
2941 return dyn_cast_or_null<BasicBlock>(
2942 getVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2943}
2944
2945/// defineBB - Define the specified basic block, which is either named or
2946/// unnamed. If there is an error, this returns null otherwise it returns
2947/// the block being defined.
2948BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
2949 int NameID, LocTy Loc) {
2950 BasicBlock *BB;
2951 if (Name.empty()) {
2952 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
2953 P.error(Loc, "label expected to be numbered '" +
2954 Twine(NumberedVals.size()) + "'");
2955 return nullptr;
2956 }
2957 BB = getBB(NumberedVals.size(), Loc);
2958 if (!BB) {
2959 P.error(Loc, "unable to create block numbered '" +
2960 Twine(NumberedVals.size()) + "'");
2961 return nullptr;
2962 }
2963 } else {
2964 BB = getBB(Name, Loc);
2965 if (!BB) {
2966 P.error(Loc, "unable to create block named '" + Name + "'");
2967 return nullptr;
2968 }
2969 }
2970
2971 // Move the block to the end of the function. Forward ref'd blocks are
2972 // inserted wherever they happen to be referenced.
2973 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2974
2975 // Remove the block from forward ref sets.
2976 if (Name.empty()) {
2977 ForwardRefValIDs.erase(NumberedVals.size());
2978 NumberedVals.push_back(BB);
2979 } else {
2980 // BB forward references are already in the function symbol table.
2981 ForwardRefVals.erase(Name);
2982 }
2983
2984 return BB;
2985}
2986
2987//===----------------------------------------------------------------------===//
2988// Constants.
2989//===----------------------------------------------------------------------===//
2990
2991/// parseValID - parse an abstract value that doesn't necessarily have a
2992/// type implied. For example, if we parse "4" we don't know what integer type
2993/// it has. The value will later be combined with its type and checked for
2994/// sanity. PFS is used to convert function-local operands of metadata (since
2995/// metadata operands are not just parsed here but also converted to values).
2996/// PFS can be null when we are not parsing metadata values inside a function.
2997bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
2998 ID.Loc = Lex.getLoc();
2999 switch (Lex.getKind()) {
1
Control jumps to 'case kw_dso_local_equivalent:' at line 3258
3000 default:
3001 return tokError("expected value token");
3002 case lltok::GlobalID: // @42
3003 ID.UIntVal = Lex.getUIntVal();
3004 ID.Kind = ValID::t_GlobalID;
3005 break;
3006 case lltok::GlobalVar: // @foo
3007 ID.StrVal = Lex.getStrVal();
3008 ID.Kind = ValID::t_GlobalName;
3009 break;
3010 case lltok::LocalVarID: // %42
3011 ID.UIntVal = Lex.getUIntVal();
3012 ID.Kind = ValID::t_LocalID;
3013 break;
3014 case lltok::LocalVar: // %foo
3015 ID.StrVal = Lex.getStrVal();
3016 ID.Kind = ValID::t_LocalName;
3017 break;
3018 case lltok::APSInt:
3019 ID.APSIntVal = Lex.getAPSIntVal();
3020 ID.Kind = ValID::t_APSInt;
3021 break;
3022 case lltok::APFloat:
3023 ID.APFloatVal = Lex.getAPFloatVal();
3024 ID.Kind = ValID::t_APFloat;
3025 break;
3026 case lltok::kw_true:
3027 ID.ConstantVal = ConstantInt::getTrue(Context);
3028 ID.Kind = ValID::t_Constant;
3029 break;
3030 case lltok::kw_false:
3031 ID.ConstantVal = ConstantInt::getFalse(Context);
3032 ID.Kind = ValID::t_Constant;
3033 break;
3034 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3035 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3036 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3037 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3038 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3039
3040 case lltok::lbrace: {
3041 // ValID ::= '{' ConstVector '}'
3042 Lex.Lex();
3043 SmallVector<Constant*, 16> Elts;
3044 if (parseGlobalValueVector(Elts) ||
3045 parseToken(lltok::rbrace, "expected end of struct constant"))
3046 return true;
3047
3048 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3049 ID.UIntVal = Elts.size();
3050 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3051 Elts.size() * sizeof(Elts[0]));
3052 ID.Kind = ValID::t_ConstantStruct;
3053 return false;
3054 }
3055 case lltok::less: {
3056 // ValID ::= '<' ConstVector '>' --> Vector.
3057 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3058 Lex.Lex();
3059 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3060
3061 SmallVector<Constant*, 16> Elts;
3062 LocTy FirstEltLoc = Lex.getLoc();
3063 if (parseGlobalValueVector(Elts) ||
3064 (isPackedStruct &&
3065 parseToken(lltok::rbrace, "expected end of packed struct")) ||
3066 parseToken(lltok::greater, "expected end of constant"))
3067 return true;
3068
3069 if (isPackedStruct) {
3070 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3071 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3072 Elts.size() * sizeof(Elts[0]));
3073 ID.UIntVal = Elts.size();
3074 ID.Kind = ValID::t_PackedConstantStruct;
3075 return false;
3076 }
3077
3078 if (Elts.empty())
3079 return error(ID.Loc, "constant vector must not be empty");
3080
3081 if (!Elts[0]->getType()->isIntegerTy() &&
3082 !Elts[0]->getType()->isFloatingPointTy() &&
3083 !Elts[0]->getType()->isPointerTy())
3084 return error(
3085 FirstEltLoc,
3086 "vector elements must have integer, pointer or floating point type");
3087
3088 // Verify that all the vector elements have the same type.
3089 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3090 if (Elts[i]->getType() != Elts[0]->getType())
3091 return error(FirstEltLoc, "vector element #" + Twine(i) +
3092 " is not of type '" +
3093 getTypeString(Elts[0]->getType()));
3094
3095 ID.ConstantVal = ConstantVector::get(Elts);
3096 ID.Kind = ValID::t_Constant;
3097 return false;
3098 }
3099 case lltok::lsquare: { // Array Constant
3100 Lex.Lex();
3101 SmallVector<Constant*, 16> Elts;
3102 LocTy FirstEltLoc = Lex.getLoc();
3103 if (parseGlobalValueVector(Elts) ||
3104 parseToken(lltok::rsquare, "expected end of array constant"))
3105 return true;
3106
3107 // Handle empty element.
3108 if (Elts.empty()) {
3109 // Use undef instead of an array because it's inconvenient to determine
3110 // the element type at this point, there being no elements to examine.
3111 ID.Kind = ValID::t_EmptyArray;
3112 return false;
3113 }
3114
3115 if (!Elts[0]->getType()->isFirstClassType())
3116 return error(FirstEltLoc, "invalid array element type: " +
3117 getTypeString(Elts[0]->getType()));
3118
3119 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3120
3121 // Verify all elements are correct type!
3122 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3123 if (Elts[i]->getType() != Elts[0]->getType())
3124 return error(FirstEltLoc, "array element #" + Twine(i) +
3125 " is not of type '" +
3126 getTypeString(Elts[0]->getType()));
3127 }
3128
3129 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3130 ID.Kind = ValID::t_Constant;
3131 return false;
3132 }
3133 case lltok::kw_c: // c "foo"
3134 Lex.Lex();
3135 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3136 false);
3137 if (parseToken(lltok::StringConstant, "expected string"))
3138 return true;
3139 ID.Kind = ValID::t_Constant;
3140 return false;
3141
3142 case lltok::kw_asm: {
3143 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3144 // STRINGCONSTANT
3145 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3146 Lex.Lex();
3147 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3148 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3149 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3150 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
3151 parseStringConstant(ID.StrVal) ||
3152 parseToken(lltok::comma, "expected comma in inline asm expression") ||
3153 parseToken(lltok::StringConstant, "expected constraint string"))
3154 return true;
3155 ID.StrVal2 = Lex.getStrVal();
3156 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
3157 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
3158 ID.Kind = ValID::t_InlineAsm;
3159 return false;
3160 }
3161
3162 case lltok::kw_blockaddress: {
3163 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3164 Lex.Lex();
3165
3166 ValID Fn, Label;
3167
3168 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3169 parseValID(Fn, PFS) ||
3170 parseToken(lltok::comma,
3171 "expected comma in block address expression") ||
3172 parseValID(Label, PFS) ||
3173 parseToken(lltok::rparen, "expected ')' in block address expression"))
3174 return true;
3175
3176 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3177 return error(Fn.Loc, "expected function name in blockaddress");
3178 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3179 return error(Label.Loc, "expected basic block name in blockaddress");
3180
3181 // Try to find the function (but skip it if it's forward-referenced).
3182 GlobalValue *GV = nullptr;
3183 if (Fn.Kind == ValID::t_GlobalID) {
3184 if (Fn.UIntVal < NumberedVals.size())
3185 GV = NumberedVals[Fn.UIntVal];
3186 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3187 GV = M->getNamedValue(Fn.StrVal);
3188 }
3189 Function *F = nullptr;
3190 if (GV) {
3191 // Confirm that it's actually a function with a definition.
3192 if (!isa<Function>(GV))
3193 return error(Fn.Loc, "expected function name in blockaddress");
3194 F = cast<Function>(GV);
3195 if (F->isDeclaration())
3196 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3197 }
3198
3199 if (!F) {
3200 // Make a global variable as a placeholder for this reference.
3201 GlobalValue *&FwdRef =
3202 ForwardRefBlockAddresses.insert(std::make_pair(
3203 std::move(Fn),
3204 std::map<ValID, GlobalValue *>()))
3205 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3206 .first->second;
3207 if (!FwdRef) {
3208 unsigned FwdDeclAS;
3209 if (ExpectedTy) {
3210 // If we know the type that the blockaddress is being assigned to,
3211 // we can use the address space of that type.
3212 if (!ExpectedTy->isPointerTy())
3213 return error(ID.Loc,
3214 "type of blockaddress must be a pointer and not '" +
3215 getTypeString(ExpectedTy) + "'");
3216 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
3217 } else if (PFS) {
3218 // Otherwise, we default the address space of the current function.
3219 FwdDeclAS = PFS->getFunction().getAddressSpace();
3220 } else {
3221 llvm_unreachable("Unknown address space for blockaddress")__builtin_unreachable();
3222 }
3223 FwdRef = new GlobalVariable(
3224 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
3225 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
3226 }
3227
3228 ID.ConstantVal = FwdRef;
3229 ID.Kind = ValID::t_Constant;
3230 return false;
3231 }
3232
3233 // We found the function; now find the basic block. Don't use PFS, since we
3234 // might be inside a constant expression.
3235 BasicBlock *BB;
3236 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3237 if (Label.Kind == ValID::t_LocalID)
3238 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
3239 else
3240 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
3241 if (!BB)
3242 return error(Label.Loc, "referenced value is not a basic block");
3243 } else {
3244 if (Label.Kind == ValID::t_LocalID)
3245 return error(Label.Loc, "cannot take address of numeric label after "
3246 "the function is defined");
3247 BB = dyn_cast_or_null<BasicBlock>(
3248 F->getValueSymbolTable()->lookup(Label.StrVal));
3249 if (!BB)
3250 return error(Label.Loc, "referenced value is not a basic block");
3251 }
3252
3253 ID.ConstantVal = BlockAddress::get(F, BB);
3254 ID.Kind = ValID::t_Constant;
3255 return false;
3256 }
3257
3258 case lltok::kw_dso_local_equivalent: {
3259 // ValID ::= 'dso_local_equivalent' @foo
3260 Lex.Lex();
3261
3262 ValID Fn;
3263
3264 if (parseValID(Fn, PFS))
2
Assuming the condition is false
3
Taking false branch
3265 return true;
3266
3267 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
4
Assuming field 'Kind' is equal to t_GlobalID
3268 return error(Fn.Loc,
3269 "expected global value name in dso_local_equivalent");
3270
3271 // Try to find the function (but skip it if it's forward-referenced).
3272 GlobalValue *GV = nullptr;
5
'GV' initialized to a null pointer value
3273 if (Fn.Kind
5.1
Field 'Kind' is equal to t_GlobalID
== ValID::t_GlobalID) {
6
Taking true branch
3274 if (Fn.UIntVal < NumberedVals.size())
7
Assuming the condition is false
8
Taking false branch
3275 GV = NumberedVals[Fn.UIntVal];
3276 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3277 GV = M->getNamedValue(Fn.StrVal);
3278 }
3279
3280 assert(GV && "Could not find a corresponding global variable")((void)0);
3281
3282 if (!GV->getValueType()->isFunctionTy())
9
Called C++ object pointer is null
3283 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
3284 "in dso_local_equivalent");
3285
3286 ID.ConstantVal = DSOLocalEquivalent::get(GV);
3287 ID.Kind = ValID::t_Constant;
3288 return false;
3289 }
3290
3291 case lltok::kw_trunc:
3292 case lltok::kw_zext:
3293 case lltok::kw_sext:
3294 case lltok::kw_fptrunc:
3295 case lltok::kw_fpext:
3296 case lltok::kw_bitcast:
3297 case lltok::kw_addrspacecast:
3298 case lltok::kw_uitofp:
3299 case lltok::kw_sitofp:
3300 case lltok::kw_fptoui:
3301 case lltok::kw_fptosi:
3302 case lltok::kw_inttoptr:
3303 case lltok::kw_ptrtoint: {
3304 unsigned Opc = Lex.getUIntVal();
3305 Type *DestTy = nullptr;
3306 Constant *SrcVal;
3307 Lex.Lex();
3308 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3309 parseGlobalTypeAndValue(SrcVal) ||
3310 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3311 parseType(DestTy) ||
3312 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3313 return true;
3314 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3315 return error(ID.Loc, "invalid cast opcode for cast from '" +
3316 getTypeString(SrcVal->getType()) + "' to '" +
3317 getTypeString(DestTy) + "'");
3318 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3319 SrcVal, DestTy);
3320 ID.Kind = ValID::t_Constant;
3321 return false;
3322 }
3323 case lltok::kw_extractvalue: {
3324 Lex.Lex();
3325 Constant *Val;
3326 SmallVector<unsigned, 4> Indices;
3327 if (parseToken(lltok::lparen,
3328 "expected '(' in extractvalue constantexpr") ||
3329 parseGlobalTypeAndValue(Val) || parseIndexList(Indices) ||
3330 parseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3331 return true;
3332
3333 if (!Val->getType()->isAggregateType())
3334 return error(ID.Loc, "extractvalue operand must be aggregate type");
3335 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3336 return error(ID.Loc, "invalid indices for extractvalue");
3337 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3338 ID.Kind = ValID::t_Constant;
3339 return false;
3340 }
3341 case lltok::kw_insertvalue: {
3342 Lex.Lex();
3343 Constant *Val0, *Val1;
3344 SmallVector<unsigned, 4> Indices;
3345 if (parseToken(lltok::lparen, "expected '(' in insertvalue constantexpr") ||
3346 parseGlobalTypeAndValue(Val0) ||
3347 parseToken(lltok::comma,
3348 "expected comma in insertvalue constantexpr") ||
3349 parseGlobalTypeAndValue(Val1) || parseIndexList(Indices) ||
3350 parseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3351 return true;
3352 if (!Val0->getType()->isAggregateType())
3353 return error(ID.Loc, "insertvalue operand must be aggregate type");
3354 Type *IndexedType =
3355 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3356 if (!IndexedType)
3357 return error(ID.Loc, "invalid indices for insertvalue");
3358 if (IndexedType != Val1->getType())
3359 return error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3360 getTypeString(Val1->getType()) +
3361 "' instead of '" + getTypeString(IndexedType) +
3362 "'");
3363 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3364 ID.Kind = ValID::t_Constant;
3365 return false;
3366 }
3367 case lltok::kw_icmp:
3368 case lltok::kw_fcmp: {
3369 unsigned PredVal, Opc = Lex.getUIntVal();
3370 Constant *Val0, *Val1;
3371 Lex.Lex();
3372 if (parseCmpPredicate(PredVal, Opc) ||
3373 parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3374 parseGlobalTypeAndValue(Val0) ||
3375 parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3376 parseGlobalTypeAndValue(Val1) ||
3377 parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3378 return true;
3379
3380 if (Val0->getType() != Val1->getType())
3381 return error(ID.Loc, "compare operands must have the same type");
3382
3383 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3384
3385 if (Opc == Instruction::FCmp) {
3386 if (!Val0->getType()->isFPOrFPVectorTy())
3387 return error(ID.Loc, "fcmp requires floating point operands");
3388 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3389 } else {
3390 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!")((void)0);
3391 if (!Val0->getType()->isIntOrIntVectorTy() &&
3392 !Val0->getType()->isPtrOrPtrVectorTy())
3393 return error(ID.Loc, "icmp requires pointer or integer operands");
3394 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3395 }
3396 ID.Kind = ValID::t_Constant;
3397 return false;
3398 }
3399
3400 // Unary Operators.
3401 case lltok::kw_fneg: {
3402 unsigned Opc = Lex.getUIntVal();
3403 Constant *Val;
3404 Lex.Lex();
3405 if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3406 parseGlobalTypeAndValue(Val) ||
3407 parseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3408 return true;
3409
3410 // Check that the type is valid for the operator.
3411 switch (Opc) {
3412 case Instruction::FNeg:
3413 if (!Val->getType()->isFPOrFPVectorTy())
3414 return error(ID.Loc, "constexpr requires fp operands");
3415 break;
3416 default: llvm_unreachable("Unknown unary operator!")__builtin_unreachable();
3417 }
3418 unsigned Flags = 0;
3419 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3420 ID.ConstantVal = C;
3421 ID.Kind = ValID::t_Constant;
3422 return false;
3423 }
3424 // Binary Operators.
3425 case lltok::kw_add:
3426 case lltok::kw_fadd:
3427 case lltok::kw_sub:
3428 case lltok::kw_fsub:
3429 case lltok::kw_mul:
3430 case lltok::kw_fmul:
3431 case lltok::kw_udiv:
3432 case lltok::kw_sdiv:
3433 case lltok::kw_fdiv:
3434 case lltok::kw_urem:
3435 case lltok::kw_srem:
3436 case lltok::kw_frem:
3437 case lltok::kw_shl:
3438 case lltok::kw_lshr:
3439 case lltok::kw_ashr: {
3440 bool NUW = false;
3441 bool NSW = false;
3442 bool Exact = false;
3443 unsigned Opc = Lex.getUIntVal();
3444 Constant *Val0, *Val1;
3445 Lex.Lex();
3446 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3447 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3448 if (EatIfPresent(lltok::kw_nuw))
3449 NUW = true;
3450 if (EatIfPresent(lltok::kw_nsw)) {
3451 NSW = true;
3452 if (EatIfPresent(lltok::kw_nuw))
3453 NUW = true;
3454 }
3455 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3456 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3457 if (EatIfPresent(lltok::kw_exact))
3458 Exact = true;
3459 }
3460 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3461 parseGlobalTypeAndValue(Val0) ||
3462 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3463 parseGlobalTypeAndValue(Val1) ||
3464 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3465 return true;
3466 if (Val0->getType() != Val1->getType())
3467 return error(ID.Loc, "operands of constexpr must have same type");
3468 // Check that the type is valid for the operator.
3469 switch (Opc) {
3470 case Instruction::Add:
3471 case Instruction::Sub:
3472 case Instruction::Mul:
3473 case Instruction::UDiv:
3474 case Instruction::SDiv:
3475 case Instruction::URem:
3476 case Instruction::SRem:
3477 case Instruction::Shl:
3478 case Instruction::AShr:
3479 case Instruction::LShr:
3480 if (!Val0->getType()->isIntOrIntVectorTy())
3481 return error(ID.Loc, "constexpr requires integer operands");
3482 break;
3483 case Instruction::FAdd:
3484 case Instruction::FSub:
3485 case Instruction::FMul:
3486 case Instruction::FDiv:
3487 case Instruction::FRem:
3488 if (!Val0->getType()->isFPOrFPVectorTy())
3489 return error(ID.Loc, "constexpr requires fp operands");
3490 break;
3491 default: llvm_unreachable("Unknown binary operator!")__builtin_unreachable();
3492 }
3493 unsigned Flags = 0;
3494 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3495 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3496 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3497 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3498 ID.ConstantVal = C;
3499 ID.Kind = ValID::t_Constant;
3500 return false;
3501 }
3502
3503 // Logical Operations
3504 case lltok::kw_and:
3505 case lltok::kw_or:
3506 case lltok::kw_xor: {
3507 unsigned Opc = Lex.getUIntVal();
3508 Constant *Val0, *Val1;
3509 Lex.Lex();
3510 if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3511 parseGlobalTypeAndValue(Val0) ||
3512 parseToken(lltok::comma, "expected comma in logical constantexpr") ||
3513 parseGlobalTypeAndValue(Val1) ||
3514 parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3515 return true;
3516 if (Val0->getType() != Val1->getType())
3517 return error(ID.Loc, "operands of constexpr must have same type");
3518 if (!Val0->getType()->isIntOrIntVectorTy())
3519 return error(ID.Loc,
3520 "constexpr requires integer or integer vector operands");
3521 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3522 ID.Kind = ValID::t_Constant;
3523 return false;
3524 }
3525
3526 case lltok::kw_getelementptr:
3527 case lltok::kw_shufflevector:
3528 case lltok::kw_insertelement:
3529 case lltok::kw_extractelement:
3530 case lltok::kw_select: {
3531 unsigned Opc = Lex.getUIntVal();
3532 SmallVector<Constant*, 16> Elts;
3533 bool InBounds = false;
3534 Type *Ty;
3535 Lex.Lex();
3536
3537 if (Opc == Instruction::GetElementPtr)
3538 InBounds = EatIfPresent(lltok::kw_inbounds);
3539
3540 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
3541 return true;
3542
3543 LocTy ExplicitTypeLoc = Lex.getLoc();
3544 if (Opc == Instruction::GetElementPtr) {
3545 if (parseType(Ty) ||
3546 parseToken(lltok::comma, "expected comma after getelementptr's type"))
3547 return true;
3548 }
3549
3550 Optional<unsigned> InRangeOp;
3551 if (parseGlobalValueVector(
3552 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3553 parseToken(lltok::rparen, "expected ')' in constantexpr"))
3554 return true;
3555
3556 if (Opc == Instruction::GetElementPtr) {
3557 if (Elts.size() == 0 ||
3558 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3559 return error(ID.Loc, "base of getelementptr must be a pointer");
3560
3561 Type *BaseType = Elts[0]->getType();
3562 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3563 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
3564 return error(
3565 ExplicitTypeLoc,
3566 typeComparisonErrorMessage(
3567 "explicit pointee type doesn't match operand's pointee type",
3568 Ty, BasePointerType->getElementType()));
3569 }
3570
3571 unsigned GEPWidth =
3572 BaseType->isVectorTy()
3573 ? cast<FixedVectorType>(BaseType)->getNumElements()
3574 : 0;
3575
3576 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3577 for (Constant *Val : Indices) {
3578 Type *ValTy = Val->getType();
3579 if (!ValTy->isIntOrIntVectorTy())
3580 return error(ID.Loc, "getelementptr index must be an integer");
3581 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
3582 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
3583 if (GEPWidth && (ValNumEl != GEPWidth))
3584 return error(
3585 ID.Loc,
3586 "getelementptr vector index has a wrong number of elements");
3587 // GEPWidth may have been unknown because the base is a scalar,
3588 // but it is known now.
3589 GEPWidth = ValNumEl;
3590 }
3591 }
3592
3593 SmallPtrSet<Type*, 4> Visited;
3594 if (!Indices.empty() && !Ty->isSized(&Visited))
3595 return error(ID.Loc, "base element of getelementptr must be sized");
3596
3597 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3598 return error(ID.Loc, "invalid getelementptr indices");
3599
3600 if (InRangeOp) {
3601 if (*InRangeOp == 0)
3602 return error(ID.Loc,
3603 "inrange keyword may not appear on pointer operand");
3604 --*InRangeOp;
3605 }
3606
3607 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3608 InBounds, InRangeOp);
3609 } else if (Opc == Instruction::Select) {
3610 if (Elts.size() != 3)
3611 return error(ID.Loc, "expected three operands to select");
3612 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3613 Elts[2]))
3614 return error(ID.Loc, Reason);
3615 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3616 } else if (Opc == Instruction::ShuffleVector) {
3617 if (Elts.size() != 3)
3618 return error(ID.Loc, "expected three operands to shufflevector");
3619 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3620 return error(ID.Loc, "invalid operands to shufflevector");
3621 SmallVector<int, 16> Mask;
3622 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
3623 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
3624 } else if (Opc == Instruction::ExtractElement) {
3625 if (Elts.size() != 2)
3626 return error(ID.Loc, "expected two operands to extractelement");
3627 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3628 return error(ID.Loc, "invalid extractelement operands");
3629 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3630 } else {
3631 assert(Opc == Instruction::InsertElement && "Unknown opcode")((void)0);
3632 if (Elts.size() != 3)
3633 return error(ID.Loc, "expected three operands to insertelement");
3634 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3635 return error(ID.Loc, "invalid insertelement operands");
3636 ID.ConstantVal =
3637 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3638 }
3639
3640 ID.Kind = ValID::t_Constant;
3641 return false;
3642 }
3643 }
3644
3645 Lex.Lex();
3646 return false;
3647}
3648
3649/// parseGlobalValue - parse a global value with the specified type.
3650bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
3651 C = nullptr;
3652 ValID ID;
3653 Value *V = nullptr;
3654 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
3655 convertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
3656 if (V && !(C = dyn_cast<Constant>(V)))
3657 return error(ID.Loc, "global values must be constants");
3658 return Parsed;
3659}
3660
3661bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
3662 Type *Ty = nullptr;
3663 return parseType(Ty) || parseGlobalValue(Ty, V);
3664}
3665
3666bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3667 C = nullptr;
3668
3669 LocTy KwLoc = Lex.getLoc();
3670 if (!EatIfPresent(lltok::kw_comdat))
3671 return false;
3672
3673 if (EatIfPresent(lltok::lparen)) {
3674 if (Lex.getKind() != lltok::ComdatVar)
3675 return tokError("expected comdat variable");
3676 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3677 Lex.Lex();
3678 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
3679 return true;
3680 } else {
3681 if (GlobalName.empty())
3682 return tokError("comdat cannot be unnamed");
3683 C = getComdat(std::string(GlobalName), KwLoc);
3684 }
3685
3686 return false;
3687}
3688
3689/// parseGlobalValueVector
3690/// ::= /*empty*/
3691/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3692bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3693 Optional<unsigned> *InRangeOp) {
3694 // Empty list.
3695 if (Lex.getKind() == lltok::rbrace ||
3696 Lex.getKind() == lltok::rsquare ||
3697 Lex.getKind() == lltok::greater ||
3698 Lex.getKind() == lltok::rparen)
3699 return false;
3700
3701 do {
3702 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3703 *InRangeOp = Elts.size();
3704
3705 Constant *C;
3706 if (parseGlobalTypeAndValue(C))
3707 return true;
3708 Elts.push_back(C);
3709 } while (EatIfPresent(lltok::comma));
3710
3711 return false;
3712}
3713
3714bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
3715 SmallVector<Metadata *, 16> Elts;
3716 if (parseMDNodeVector(Elts))
3717 return true;
3718
3719 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3720 return false;
3721}
3722
3723/// MDNode:
3724/// ::= !{ ... }
3725/// ::= !7
3726/// ::= !DILocation(...)
3727bool LLParser::parseMDNode(MDNode *&N) {
3728 if (Lex.getKind() == lltok::MetadataVar)
3729 return parseSpecializedMDNode(N);
3730
3731 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
3732}
3733
3734bool LLParser::parseMDNodeTail(MDNode *&N) {
3735 // !{ ... }
3736 if (Lex.getKind() == lltok::lbrace)
3737 return parseMDTuple(N);
3738
3739 // !42
3740 return parseMDNodeID(N);
3741}
3742
3743namespace {
3744
3745/// Structure to represent an optional metadata field.
3746template <class FieldTy> struct MDFieldImpl {
3747 typedef MDFieldImpl ImplTy;
3748 FieldTy Val;
3749 bool Seen;
3750
3751 void assign(FieldTy Val) {
3752 Seen = true;
3753 this->Val = std::move(Val);
3754 }
3755
3756 explicit MDFieldImpl(FieldTy Default)
3757 : Val(std::move(Default)), Seen(false) {}
3758};
3759
3760/// Structure to represent an optional metadata field that
3761/// can be of either type (A or B) and encapsulates the
3762/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3763/// to reimplement the specifics for representing each Field.
3764template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3765 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3766 FieldTypeA A;
3767 FieldTypeB B;
3768 bool Seen;
3769
3770 enum {
3771 IsInvalid = 0,
3772 IsTypeA = 1,
3773 IsTypeB = 2
3774 } WhatIs;
3775
3776 void assign(FieldTypeA A) {
3777 Seen = true;
3778 this->A = std::move(A);
3779 WhatIs = IsTypeA;
3780 }
3781
3782 void assign(FieldTypeB B) {
3783 Seen = true;
3784 this->B = std::move(B);
3785 WhatIs = IsTypeB;
3786 }
3787
3788 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3789 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3790 WhatIs(IsInvalid) {}
3791};
3792
3793struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3794 uint64_t Max;
3795
3796 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX0xffffffffffffffffULL)
3797 : ImplTy(Default), Max(Max) {}
3798};
3799
3800struct LineField : public MDUnsignedField {
3801 LineField() : MDUnsignedField(0, UINT32_MAX0xffffffffU) {}
3802};
3803
3804struct ColumnField : public MDUnsignedField {
3805 ColumnField() : MDUnsignedField(0, UINT16_MAX0xffff) {}
3806};
3807
3808struct DwarfTagField : public MDUnsignedField {
3809 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3810 DwarfTagField(dwarf::Tag DefaultTag)
3811 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3812};
3813
3814struct DwarfMacinfoTypeField : public MDUnsignedField {
3815 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3816 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3817 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3818};
3819
3820struct DwarfAttEncodingField : public MDUnsignedField {
3821 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3822};
3823
3824struct DwarfVirtualityField : public MDUnsignedField {
3825 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3826};
3827
3828struct DwarfLangField : public MDUnsignedField {
3829 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3830};
3831
3832struct DwarfCCField : public MDUnsignedField {
3833 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3834};
3835
3836struct EmissionKindField : public MDUnsignedField {
3837 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3838};
3839
3840struct NameTableKindField : public MDUnsignedField {
3841 NameTableKindField()
3842 : MDUnsignedField(
3843 0, (unsigned)
3844 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3845};
3846
3847struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3848 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3849};
3850
3851struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3852 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3853};
3854
3855struct MDAPSIntField : public MDFieldImpl<APSInt> {
3856 MDAPSIntField() : ImplTy(APSInt()) {}
3857};
3858
3859struct MDSignedField : public MDFieldImpl<int64_t> {
3860 int64_t Min;
3861 int64_t Max;
3862
3863 MDSignedField(int64_t Default = 0)
3864 : ImplTy(Default), Min(INT64_MIN(-0x7fffffffffffffffLL - 1)), Max(INT64_MAX0x7fffffffffffffffLL) {}
3865 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3866 : ImplTy(Default), Min(Min), Max(Max) {}
3867};
3868
3869struct MDBoolField : public MDFieldImpl<bool> {
3870 MDBoolField(bool Default = false) : ImplTy(Default) {}
3871};
3872
3873struct MDField : public MDFieldImpl<Metadata *> {
3874 bool AllowNull;
3875
3876 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3877};
3878
3879struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3880 MDConstant() : ImplTy(nullptr) {}
3881};
3882
3883struct MDStringField : public MDFieldImpl<MDString *> {
3884 bool AllowEmpty;
3885 MDStringField(bool AllowEmpty = true)
3886 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3887};
3888
3889struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3890 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3891};
3892
3893struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3894 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3895};
3896
3897struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3898 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3899 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3900
3901 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3902 bool AllowNull = true)
3903 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3904
3905 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3906 bool isMDField() const { return WhatIs == IsTypeB; }
3907 int64_t getMDSignedValue() const {
3908 assert(isMDSignedField() && "Wrong field type")((void)0);
3909 return A.Val;
3910 }
3911 Metadata *getMDFieldValue() const {
3912 assert(isMDField() && "Wrong field type")((void)0);
3913 return B.Val;
3914 }
3915};
3916
3917struct MDSignedOrUnsignedField
3918 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3919 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3920
3921 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3922 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3923 int64_t getMDSignedValue() const {
3924 assert(isMDSignedField() && "Wrong field type")((void)0);
3925 return A.Val;
3926 }
3927 uint64_t getMDUnsignedValue() const {
3928 assert(isMDUnsignedField() && "Wrong field type")((void)0);
3929 return B.Val;
3930 }
3931};
3932
3933} // end anonymous namespace
3934
3935namespace llvm {
3936
3937template <>
3938bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
3939 if (Lex.getKind() != lltok::APSInt)
3940 return tokError("expected integer");
3941
3942 Result.assign(Lex.getAPSIntVal());
3943 Lex.Lex();
3944 return false;
3945}
3946
3947template <>
3948bool LLParser::parseMDField(LocTy Loc, StringRef Name,
3949 MDUnsignedField &Result) {
3950 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3951 return tokError("expected unsigned integer");
3952
3953 auto &U = Lex.getAPSIntVal();
3954 if (U.ugt(Result.Max))
3955 return tokError("value for '" + Name + "' too large, limit is " +
3956 Twine(Result.Max));
3957 Result.assign(U.getZExtValue());
3958 assert(Result.Val <= Result.Max && "Expected value in range")((void)0);
3959 Lex.Lex();
3960 return false;
3961}
3962
3963template <>
3964bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3965 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3966}
3967template <>
3968bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3969 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3970}
3971
3972template <>
3973bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3974 if (Lex.getKind() == lltok::APSInt)
3975 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3976
3977 if (Lex.getKind() != lltok::DwarfTag)
3978 return tokError("expected DWARF tag");
3979
3980 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3981 if (Tag == dwarf::DW_TAG_invalid)
3982 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3983 assert(Tag <= Result.Max && "Expected valid DWARF tag")((void)0);
3984
3985 Result.assign(Tag);
3986 Lex.Lex();
3987 return false;
3988}
3989
3990template <>
3991bool LLParser::parseMDField(LocTy Loc, StringRef Name,
3992 DwarfMacinfoTypeField &Result) {
3993 if (Lex.getKind() == lltok::APSInt)
3994 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3995
3996 if (Lex.getKind() != lltok::DwarfMacinfo)
3997 return tokError("expected DWARF macinfo type");
3998
3999 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4000 if (Macinfo == dwarf::DW_MACINFO_invalid)
4001 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4002 Lex.getStrVal() + "'");
4003 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type")((void)0);
4004
4005 Result.assign(Macinfo);
4006 Lex.Lex();
4007 return false;
4008}
4009
4010template <>
4011bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4012 DwarfVirtualityField &Result) {
4013 if (Lex.getKind() == lltok::APSInt)
4014 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4015
4016 if (Lex.getKind() != lltok::DwarfVirtuality)
4017 return tokError("expected DWARF virtuality code");
4018
4019 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4020 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4021 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4022 Lex.getStrVal() + "'");
4023 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code")((void)0);
4024 Result.assign(Virtuality);
4025 Lex.Lex();
4026 return false;
4027}
4028
4029template <>
4030bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4031 if (Lex.getKind() == lltok::APSInt)
4032 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4033
4034 if (Lex.getKind() != lltok::DwarfLang)
4035 return tokError("expected DWARF language");
4036
4037 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4038 if (!Lang)
4039 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4040 "'");
4041 assert(Lang <= Result.Max && "Expected valid DWARF language")((void)0);
4042 Result.assign(Lang);
4043 Lex.Lex();
4044 return false;
4045}
4046
4047template <>
4048bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4049 if (Lex.getKind() == lltok::APSInt)
4050 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4051
4052 if (Lex.getKind() != lltok::DwarfCC)
4053 return tokError("expected DWARF calling convention");
4054
4055 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4056 if (!CC)
4057 return tokError("invalid DWARF calling convention" + Twine(" '") +
4058 Lex.getStrVal() + "'");
4059 assert(CC <= Result.Max && "Expected valid DWARF calling convention")((void)0);
4060 Result.assign(CC);
4061 Lex.Lex();
4062 return false;
4063}
4064
4065template <>
4066bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4067 EmissionKindField &Result) {
4068 if (Lex.getKind() == lltok::APSInt)
4069 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4070
4071 if (Lex.getKind() != lltok::EmissionKind)
4072 return tokError("expected emission kind");
4073
4074 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4075 if (!Kind)
4076 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4077 "'");
4078 assert(*Kind <= Result.Max && "Expected valid emission kind")((void)0);
4079 Result.assign(*Kind);
4080 Lex.Lex();
4081 return false;
4082}
4083
4084template <>
4085bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4086 NameTableKindField &Result) {
4087 if (Lex.getKind() == lltok::APSInt)
4088 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4089
4090 if (Lex.getKind() != lltok::NameTableKind)
4091 return tokError("expected nameTable kind");
4092
4093 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4094 if (!Kind)
4095 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4096 "'");
4097 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind")((void)0);
4098 Result.assign((unsigned)*Kind);
4099 Lex.Lex();
4100 return false;
4101}
4102
4103template <>
4104bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4105 DwarfAttEncodingField &Result) {
4106 if (Lex.getKind() == lltok::APSInt)
4107 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4108
4109 if (Lex.getKind() != lltok::DwarfAttEncoding)
4110 return tokError("expected DWARF type attribute encoding");
4111
4112 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4113 if (!Encoding)
4114 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4115 Lex.getStrVal() + "'");
4116 assert(Encoding <= Result.Max && "Expected valid DWARF language")((void)0);
4117 Result.assign(Encoding);
4118 Lex.Lex();
4119 return false;
4120}
4121
4122/// DIFlagField
4123/// ::= uint32
4124/// ::= DIFlagVector
4125/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4126template <>
4127bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4128
4129 // parser for a single flag.
4130 auto parseFlag = [&](DINode::DIFlags &Val) {
4131 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4132 uint32_t TempVal = static_cast<uint32_t>(Val);
4133 bool Res = parseUInt32(TempVal);
4134 Val = static_cast<DINode::DIFlags>(TempVal);
4135 return Res;
4136 }
4137
4138 if (Lex.getKind() != lltok::DIFlag)
4139 return tokError("expected debug info flag");
4140
4141 Val = DINode::getFlag(Lex.getStrVal());
4142 if (!Val)
4143 return tokError(Twine("invalid debug info flag flag '") +
4144 Lex.getStrVal() + "'");
4145 Lex.Lex();
4146 return false;
4147 };
4148
4149 // parse the flags and combine them together.
4150 DINode::DIFlags Combined = DINode::FlagZero;
4151 do {
4152 DINode::DIFlags Val;
4153 if (parseFlag(Val))
4154 return true;
4155 Combined |= Val;
4156 } while (EatIfPresent(lltok::bar));
4157
4158 Result.assign(Combined);
4159 return false;
4160}
4161
4162/// DISPFlagField
4163/// ::= uint32
4164/// ::= DISPFlagVector
4165/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4166template <>
4167bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4168
4169 // parser for a single flag.
4170 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4171 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4172 uint32_t TempVal = static_cast<uint32_t>(Val);
4173 bool Res = parseUInt32(TempVal);
4174 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4175 return Res;
4176 }
4177
4178 if (Lex.getKind() != lltok::DISPFlag)
4179 return tokError("expected debug info flag");
4180
4181 Val = DISubprogram::getFlag(Lex.getStrVal());
4182 if (!Val)
4183 return tokError(Twine("invalid subprogram debug info flag '") +
4184 Lex.getStrVal() + "'");
4185 Lex.Lex();
4186 return false;
4187 };
4188
4189 // parse the flags and combine them together.
4190 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4191 do {
4192 DISubprogram::DISPFlags Val;
4193 if (parseFlag(Val))
4194 return true;
4195 Combined |= Val;
4196 } while (EatIfPresent(lltok::bar));
4197
4198 Result.assign(Combined);
4199 return false;
4200}
4201
4202template <>
4203bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4204 if (Lex.getKind() != lltok::APSInt)
4205 return tokError("expected signed integer");
4206
4207 auto &S = Lex.getAPSIntVal();
4208 if (S < Result.Min)
4209 return tokError("value for '" + Name + "' too small, limit is " +
4210 Twine(Result.Min));
4211 if (S > Result.Max)
4212 return tokError("value for '" + Name + "' too large, limit is " +
4213 Twine(Result.Max));
4214 Result.assign(S.getExtValue());
4215 assert(Result.Val >= Result.Min && "Expected value in range")((void)0);
4216 assert(Result.Val <= Result.Max && "Expected value in range")((void)0);
4217 Lex.Lex();
4218 return false;
4219}
4220
4221template <>
4222bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4223 switch (Lex.getKind()) {
4224 default:
4225 return tokError("expected 'true' or 'false'");
4226 case lltok::kw_true:
4227 Result.assign(true);
4228 break;
4229 case lltok::kw_false:
4230 Result.assign(false);
4231 break;
4232 }
4233 Lex.Lex();
4234 return false;
4235}
4236
4237template <>
4238bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4239 if (Lex.getKind() == lltok::kw_null) {
4240 if (!Result.AllowNull)
4241 return tokError("'" + Name + "' cannot be null");
4242 Lex.Lex();
4243 Result.assign(nullptr);
4244 return false;
4245 }
4246
4247 Metadata *MD;
4248 if (parseMetadata(MD, nullptr))
4249 return true;
4250
4251 Result.assign(MD);
4252 return false;
4253}
4254
4255template <>
4256bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4257 MDSignedOrMDField &Result) {
4258 // Try to parse a signed int.
4259 if (Lex.getKind() == lltok::APSInt) {
4260 MDSignedField Res = Result.A;
4261 if (!parseMDField(Loc, Name, Res)) {
4262 Result.assign(Res);
4263 return false;
4264 }
4265 return true;
4266 }
4267
4268 // Otherwise, try to parse as an MDField.
4269 MDField Res = Result.B;
4270 if (!parseMDField(Loc, Name, Res)) {
4271 Result.assign(Res);
4272 return false;
4273 }
4274
4275 return true;
4276}
4277
4278template <>
4279bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4280 LocTy ValueLoc = Lex.getLoc();
4281 std::string S;
4282 if (parseStringConstant(S))
4283 return true;
4284
4285 if (!Result.AllowEmpty && S.empty())
4286 return error(ValueLoc, "'" + Name + "' cannot be empty");
4287
4288 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4289 return false;
4290}
4291
4292template <>
4293bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4294 SmallVector<Metadata *, 4> MDs;
4295 if (parseMDNodeVector(MDs))
4296 return true;
4297
4298 Result.assign(std::move(MDs));
4299 return false;
4300}
4301
4302template <>
4303bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4304 ChecksumKindField &Result) {
4305 Optional<DIFile::ChecksumKind> CSKind =
4306 DIFile::getChecksumKind(Lex.getStrVal());
4307
4308 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4309 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4310 "'");
4311
4312 Result.assign(*CSKind);
4313 Lex.Lex();
4314 return false;
4315}
4316
4317} // end namespace llvm
4318
4319template <class ParserTy>
4320bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4321 do {
4322 if (Lex.getKind() != lltok::LabelStr)
4323 return tokError("expected field label here");
4324
4325 if (ParseField())
4326 return true;
4327 } while (EatIfPresent(lltok::comma));
4328
4329 return false;
4330}
4331
4332template <class ParserTy>
4333bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4334 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((void)0);
4335 Lex.Lex();
4336
4337 if (parseToken(lltok::lparen, "expected '(' here"))
4338 return true;
4339 if (Lex.getKind() != lltok::rparen)
4340 if (parseMDFieldsImplBody(ParseField))
4341 return true;
4342
4343 ClosingLoc = Lex.getLoc();
4344 return parseToken(lltok::rparen, "expected ')' here");
4345}
4346
4347template <class FieldTy>
4348bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4349 if (Result.Seen)
4350 return tokError("field '" + Name + "' cannot be specified more than once");
4351
4352 LocTy Loc = Lex.getLoc();
4353 Lex.Lex();
4354 return parseMDField(Loc, Name, Result);
4355}
4356
4357bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4358 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((void)0);
4359
4360#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4361 if (Lex.getStrVal() == #CLASS) \
4362 return parse##CLASS(N, IsDistinct);
4363#include "llvm/IR/Metadata.def"
4364
4365 return tokError("expected metadata type");
4366}
4367
4368#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4369#define NOP_FIELD(NAME, TYPE, INIT)
4370#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4371 if (!NAME.Seen) \
4372 return error(ClosingLoc, "missing required field '" #NAME "'");
4373#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4374 if (Lex.getStrVal() == #NAME) \
4375 return parseMDField(#NAME, NAME);
4376#define PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
\
4377 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4378 do { \
4379 LocTy ClosingLoc; \
4380 if (parseMDFieldsImpl( \
4381 [&]() -> bool { \
4382 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4383 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
4384 "'"); \
4385 }, \
4386 ClosingLoc)) \
4387 return true; \
4388 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4389 } while (false)
4390#define GET_OR_DISTINCT(CLASS, ARGS)(IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) \
4391 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4392
4393/// parseDILocationFields:
4394/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4395/// isImplicitCode: true)
4396bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4397#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4398 OPTIONAL(line, LineField, ); \
4399 OPTIONAL(column, ColumnField, ); \
4400 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4401 OPTIONAL(inlinedAt, MDField, ); \
4402 OPTIONAL(isImplicitCode, MDBoolField, (false));
4403 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4404#undef VISIT_MD_FIELDS
4405
4406 Result =
4407 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,(IsDistinct ? DILocation::getDistinct (Context, line.Val, column
.Val, scope.Val, inlinedAt.Val, isImplicitCode.Val) : DILocation
::get (Context, line.Val, column.Val, scope.Val, inlinedAt.Val
, isImplicitCode.Val))
4408 inlinedAt.Val, isImplicitCode.Val))(IsDistinct ? DILocation::getDistinct (Context, line.Val, column
.Val, scope.Val, inlinedAt.Val, isImplicitCode.Val) : DILocation
::get (Context, line.Val, column.Val, scope.Val, inlinedAt.Val
, isImplicitCode.Val))
;
4409 return false;
4410}
4411
4412/// parseGenericDINode:
4413/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4414bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4415#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4416 REQUIRED(tag, DwarfTagField, ); \
4417 OPTIONAL(header, MDStringField, ); \
4418 OPTIONAL(operands, MDFieldList, );
4419 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4420#undef VISIT_MD_FIELDS
4421
4422 Result = GET_OR_DISTINCT(GenericDINode,(IsDistinct ? GenericDINode::getDistinct (Context, tag.Val, header
.Val, operands.Val) : GenericDINode::get (Context, tag.Val, header
.Val, operands.Val))
4423 (Context, tag.Val, header.Val, operands.Val))(IsDistinct ? GenericDINode::getDistinct (Context, tag.Val, header
.Val, operands.Val) : GenericDINode::get (Context, tag.Val, header
.Val, operands.Val))
;
4424 return false;
4425}
4426
4427/// parseDISubrange:
4428/// ::= !DISubrange(count: 30, lowerBound: 2)
4429/// ::= !DISubrange(count: !node, lowerBound: 2)
4430/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4431bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4432#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4433 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX0x7fffffffffffffffLL, false)); \
4434 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4435 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4436 OPTIONAL(stride, MDSignedOrMDField, );
4437 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4438#undef VISIT_MD_FIELDS
4439
4440 Metadata *Count = nullptr;
4441 Metadata *LowerBound = nullptr;
4442 Metadata *UpperBound = nullptr;
4443 Metadata *Stride = nullptr;
4444
4445 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4446 if (Bound.isMDSignedField())
4447 return ConstantAsMetadata::get(ConstantInt::getSigned(
4448 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4449 if (Bound.isMDField())
4450 return Bound.getMDFieldValue();
4451 return nullptr;
4452 };
4453
4454 Count = convToMetadata(count);
4455 LowerBound = convToMetadata(lowerBound);
4456 UpperBound = convToMetadata(upperBound);
4457 Stride = convToMetadata(stride);
4458
4459 Result = GET_OR_DISTINCT(DISubrange,(IsDistinct ? DISubrange::getDistinct (Context, Count, LowerBound
, UpperBound, Stride) : DISubrange::get (Context, Count, LowerBound
, UpperBound, Stride))
4460 (Context, Count, LowerBound, UpperBound, Stride))(IsDistinct ? DISubrange::getDistinct (Context, Count, LowerBound
, UpperBound, Stride) : DISubrange::get (Context, Count, LowerBound
, UpperBound, Stride))
;
4461
4462 return false;
4463}
4464
4465/// parseDIGenericSubrange:
4466/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4467/// !node3)
4468bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4469#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4470 OPTIONAL(count, MDSignedOrMDField, ); \
4471 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4472 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4473 OPTIONAL(stride, MDSignedOrMDField, );
4474 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4475#undef VISIT_MD_FIELDS
4476
4477 auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4478 if (Bound.isMDSignedField())
4479 return DIExpression::get(
4480 Context, {dwarf::DW_OP_consts,
4481 static_cast<uint64_t>(Bound.getMDSignedValue())});
4482 if (Bound.isMDField())
4483 return Bound.getMDFieldValue();
4484 return nullptr;
4485 };
4486
4487 Metadata *Count = ConvToMetadata(count);
4488 Metadata *LowerBound = ConvToMetadata(lowerBound);
4489 Metadata *UpperBound = ConvToMetadata(upperBound);
4490 Metadata *Stride = ConvToMetadata(stride);
4491
4492 Result = GET_OR_DISTINCT(DIGenericSubrange,(IsDistinct ? DIGenericSubrange::getDistinct (Context, Count,
LowerBound, UpperBound, Stride) : DIGenericSubrange::get (Context
, Count, LowerBound, UpperBound, Stride))
4493 (Context, Count, LowerBound, UpperBound, Stride))(IsDistinct ? DIGenericSubrange::getDistinct (Context, Count,
LowerBound, UpperBound, Stride) : DIGenericSubrange::get (Context
, Count, LowerBound, UpperBound, Stride))
;
4494
4495 return false;
4496}
4497
4498/// parseDIEnumerator:
4499/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4500bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4501#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4502 REQUIRED(name, MDStringField, ); \
4503 REQUIRED(value, MDAPSIntField, ); \
4504 OPTIONAL(isUnsigned, MDBoolField, (false));
4505 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4506#undef VISIT_MD_FIELDS
4507
4508 if (isUnsigned.Val && value.Val.isNegative())
4509 return tokError("unsigned enumerator with negative value");
4510
4511 APSInt Value(value.Val);
4512 // Add a leading zero so that unsigned values with the msb set are not
4513 // mistaken for negative values when used for signed enumerators.
4514 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
4515 Value = Value.zext(Value.getBitWidth() + 1);
4516
4517 Result =
4518 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val))(IsDistinct ? DIEnumerator::getDistinct (Context, Value, isUnsigned
.Val, name.Val) : DIEnumerator::get (Context, Value, isUnsigned
.Val, name.Val))
;
4519
4520 return false;
4521}
4522
4523/// parseDIBasicType:
4524/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4525/// encoding: DW_ATE_encoding, flags: 0)
4526bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
4527#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4528 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4529 OPTIONAL(name, MDStringField, ); \
4530 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX0xffffffffffffffffULL)); \
4531 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
4532 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4533 OPTIONAL(flags, DIFlagField, );
4534 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4535#undef VISIT_MD_FIELDS
4536
4537 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,(IsDistinct ? DIBasicType::getDistinct (Context, tag.Val, name
.Val, size.Val, align.Val, encoding.Val, flags.Val) : DIBasicType
::get (Context, tag.Val, name.Val, size.Val, align.Val, encoding
.Val, flags.Val))
4538 align.Val, encoding.Val, flags.Val))(IsDistinct ? DIBasicType::getDistinct (Context, tag.Val, name
.Val, size.Val, align.Val, encoding.Val, flags.Val) : DIBasicType
::get (Context, tag.Val, name.Val, size.Val, align.Val, encoding
.Val, flags.Val))
;
4539 return false;
4540}
4541
4542/// parseDIStringType:
4543/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
4544bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
4545#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4546 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
4547 OPTIONAL(name, MDStringField, ); \
4548 OPTIONAL(stringLength, MDField, ); \
4549 OPTIONAL(stringLengthExpression, MDField, ); \
4550 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX0xffffffffffffffffULL)); \
4551 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
4552 OPTIONAL(encoding, DwarfAttEncodingField, );
4553 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4554#undef VISIT_MD_FIELDS
4555
4556 Result = GET_OR_DISTINCT(DIStringType,(IsDistinct ? DIStringType::getDistinct (Context, tag.Val, name
.Val, stringLength.Val, stringLengthExpression.Val, size.Val,
align.Val, encoding.Val) : DIStringType::get (Context, tag.Val
, name.Val, stringLength.Val, stringLengthExpression.Val, size
.Val, align.Val, encoding.Val))
4557 (Context, tag.Val, name.Val, stringLength.Val,(IsDistinct ? DIStringType::getDistinct (Context, tag.Val, name
.Val, stringLength.Val, stringLengthExpression.Val, size.Val,
align.Val, encoding.Val) : DIStringType::get (Context, tag.Val
, name.Val, stringLength.Val, stringLengthExpression.Val, size
.Val, align.Val, encoding.Val))
4558 stringLengthExpression.Val, size.Val, align.Val,(IsDistinct ? DIStringType::getDistinct (Context, tag.Val, name
.Val, stringLength.Val, stringLengthExpression.Val, size.Val,
align.Val, encoding.Val) : DIStringType::get (Context, tag.Val
, name.Val, stringLength.Val, stringLengthExpression.Val, size
.Val, align.Val, encoding.Val))
4559 encoding.Val))(IsDistinct ? DIStringType::getDistinct (Context, tag.Val, name
.Val, stringLength.Val, stringLengthExpression.Val, size.Val,
align.Val, encoding.Val) : DIStringType::get (Context, tag.Val
, name.Val, stringLength.Val, stringLengthExpression.Val, size
.Val, align.Val, encoding.Val))
;
4560 return false;
4561}
4562
4563/// parseDIDerivedType:
4564/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4565/// line: 7, scope: !1, baseType: !2, size: 32,
4566/// align: 32, offset: 0, flags: 0, extraData: !3,
4567/// dwarfAddressSpace: 3)
4568bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4569#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4570 REQUIRED(tag, DwarfTagField, ); \
4571 OPTIONAL(name, MDStringField, ); \
4572 OPTIONAL(file, MDField, ); \
4573 OPTIONAL(line, LineField, ); \
4574 OPTIONAL(scope, MDField, ); \
4575 REQUIRED(baseType, MDField, ); \
4576 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX0xffffffffffffffffULL)); \
4577 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
4578 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX0xffffffffffffffffULL)); \
4579 OPTIONAL(flags, DIFlagField, ); \
4580 OPTIONAL(extraData, MDField, ); \
4581 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX0xffffffffU, UINT32_MAX0xffffffffU));
4582 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4583#undef VISIT_MD_FIELDS
4584
4585 Optional<unsigned> DWARFAddressSpace;
4586 if (dwarfAddressSpace.Val != UINT32_MAX0xffffffffU)
4587 DWARFAddressSpace = dwarfAddressSpace.Val;
4588
4589 Result = GET_OR_DISTINCT(DIDerivedType,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4590 (Context, tag.Val, name.Val, file.Val, line.Val,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4591 scope.Val, baseType.Val, size.Val, align.Val,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4592 offset.Val, DWARFAddressSpace, flags.Val,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4593 extraData.Val))(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
;
4594 return false;
4595}
4596
4597bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
4598#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4599 REQUIRED(tag, DwarfTagField, ); \
4600 OPTIONAL(name, MDStringField, ); \
4601 OPTIONAL(file, MDField, ); \
4602 OPTIONAL(line, LineField, ); \
4603 OPTIONAL(scope, MDField, ); \
4604 OPTIONAL(baseType, MDField, ); \
4605 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX0xffffffffffffffffULL)); \
4606 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
4607 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX0xffffffffffffffffULL)); \
4608 OPTIONAL(flags, DIFlagField, ); \
4609 OPTIONAL(elements, MDField, ); \
4610 OPTIONAL(runtimeLang, DwarfLangField, ); \
4611 OPTIONAL(vtableHolder, MDField, ); \
4612 OPTIONAL(templateParams, MDField, ); \
4613 OPTIONAL(identifier, MDStringField, ); \
4614 OPTIONAL(discriminator, MDField, ); \
4615 OPTIONAL(dataLocation, MDField, ); \
4616 OPTIONAL(associated, MDField, ); \
4617 OPTIONAL(allocated, MDField, ); \
4618 OPTIONAL(rank, MDSignedOrMDField, );
4619 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4620#undef VISIT_MD_FIELDS
4621
4622 Metadata *Rank = nullptr;
4623 if (rank.isMDSignedField())
4624 Rank = ConstantAsMetadata::get(ConstantInt::getSigned(
4625 Type::getInt64Ty(Context), rank.getMDSignedValue()));
4626 else if (rank.isMDField())
4627 Rank = rank.getMDFieldValue();
4628
4629 // If this has an identifier try to build an ODR type.
4630 if (identifier.Val)
4631 if (auto *CT = DICompositeType::buildODRType(
4632 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4633 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4634 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
4635 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4636 Rank)) {
4637 Result = CT;
4638 return false;
4639 }
4640
4641 // Create a new node, and save it in the context if it belongs in the type
4642 // map.
4643 Result = GET_OR_DISTINCT((IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
4644 DICompositeType,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
4645 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
4646 size.Val, align.Val, offset.Val, flags.Val, elements.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
4647 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
4648 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
4649 Rank))(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val, dataLocation.Val, associated.Val, allocated.Val, Rank) :
DICompositeType::get (Context, tag.Val, name.Val, file.Val, line
.Val, scope.Val, baseType.Val, size.Val, align.Val, offset.Val
, flags.Val, elements.Val, runtimeLang.Val, vtableHolder.Val,
templateParams.Val, identifier.Val, discriminator.Val, dataLocation
.Val, associated.Val, allocated.Val, Rank))
;
4650 return false;
4651}
4652
4653bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4654#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4655 OPTIONAL(flags, DIFlagField, ); \
4656 OPTIONAL(cc, DwarfCCField, ); \
4657 REQUIRED(types, MDField, );
4658 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4659#undef VISIT_MD_FIELDS
4660
4661 Result = GET_OR_DISTINCT(DISubroutineType,(IsDistinct ? DISubroutineType::getDistinct (Context, flags.Val
, cc.Val, types.Val) : DISubroutineType::get (Context, flags.
Val, cc.Val, types.Val))
4662 (Context, flags.Val, cc.Val, types.Val))(IsDistinct ? DISubroutineType::getDistinct (Context, flags.Val
, cc.Val, types.Val) : DISubroutineType::get (Context, flags.
Val, cc.Val, types.Val))
;
4663 return false;
4664}
4665
4666/// parseDIFileType:
4667/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4668/// checksumkind: CSK_MD5,
4669/// checksum: "000102030405060708090a0b0c0d0e0f",
4670/// source: "source file contents")
4671bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
4672 // The default constructed value for checksumkind is required, but will never
4673 // be used, as the parser checks if the field was actually Seen before using
4674 // the Val.
4675#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4676 REQUIRED(filename, MDStringField, ); \
4677 REQUIRED(directory, MDStringField, ); \
4678 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4679 OPTIONAL(checksum, MDStringField, ); \
4680 OPTIONAL(source, MDStringField, );
4681 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4682#undef VISIT_MD_FIELDS
4683
4684 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4685 if (checksumkind.Seen && checksum.Seen)
4686 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4687 else if (checksumkind.Seen || checksum.Seen)
4688 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4689
4690 Optional<MDString *> OptSource;
4691 if (source.Seen)
4692 OptSource = source.Val;
4693 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,(IsDistinct ? DIFile::getDistinct (Context, filename.Val, directory
.Val, OptChecksum, OptSource) : DIFile::get (Context, filename
.Val, directory.Val, OptChecksum, OptSource))
4694 OptChecksum, OptSource))(IsDistinct ? DIFile::getDistinct (Context, filename.Val, directory
.Val, OptChecksum, OptSource) : DIFile::get (Context, filename
.Val, directory.Val, OptChecksum, OptSource))
;
4695 return false;
4696}
4697
4698/// parseDICompileUnit:
4699/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4700/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4701/// splitDebugFilename: "abc.debug",
4702/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4703/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
4704/// sysroot: "/", sdk: "MacOSX.sdk")
4705bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4706 if (!IsDistinct)
4707 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4708
4709#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4710 REQUIRED(language, DwarfLangField, ); \
4711 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4712 OPTIONAL(producer, MDStringField, ); \
4713 OPTIONAL(isOptimized, MDBoolField, ); \
4714 OPTIONAL(flags, MDStringField, ); \
4715 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
4716 OPTIONAL(splitDebugFilename, MDStringField, ); \
4717 OPTIONAL(emissionKind, EmissionKindField, ); \
4718 OPTIONAL(enums, MDField, ); \
4719 OPTIONAL(retainedTypes, MDField, ); \
4720 OPTIONAL(globals, MDField, ); \
4721 OPTIONAL(imports, MDField, ); \
4722 OPTIONAL(macros, MDField, ); \
4723 OPTIONAL(dwoId, MDUnsignedField, ); \
4724 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4725 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4726 OPTIONAL(nameTableKind, NameTableKindField, ); \
4727 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
4728 OPTIONAL(sysroot, MDStringField, ); \
4729 OPTIONAL(sdk, MDStringField, );
4730 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4731#undef VISIT_MD_FIELDS
4732
4733 Result = DICompileUnit::getDistinct(
4734 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4735 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4736 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4737 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4738 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
4739 return false;
4740}
4741
4742/// parseDISubprogram:
4743/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4744/// file: !1, line: 7, type: !2, isLocal: false,
4745/// isDefinition: true, scopeLine: 8, containingType: !3,
4746/// virtuality: DW_VIRTUALTIY_pure_virtual,
4747/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4748/// spFlags: 10, isOptimized: false, templateParams: !4,
4749/// declaration: !5, retainedNodes: !6, thrownTypes: !7)
4750bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
4751 auto Loc = Lex.getLoc();
4752#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4753 OPTIONAL(scope, MDField, ); \
4754 OPTIONAL(name, MDStringField, ); \
4755 OPTIONAL(linkageName, MDStringField, ); \
4756 OPTIONAL(file, MDField, ); \
4757 OPTIONAL(line, LineField, ); \
4758 OPTIONAL(type, MDField, ); \
4759 OPTIONAL(isLocal, MDBoolField, ); \
4760 OPTIONAL(isDefinition, MDBoolField, (true)); \
4761 OPTIONAL(scopeLine, LineField, ); \
4762 OPTIONAL(containingType, MDField, ); \
4763 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4764 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
4765 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN(-0x7fffffff - 1), INT32_MAX0x7fffffff)); \
4766 OPTIONAL(flags, DIFlagField, ); \
4767 OPTIONAL(spFlags, DISPFlagField, ); \
4768 OPTIONAL(isOptimized, MDBoolField, ); \
4769 OPTIONAL(unit, MDField, ); \
4770 OPTIONAL(templateParams, MDField, ); \
4771 OPTIONAL(declaration, MDField, ); \
4772 OPTIONAL(retainedNodes, MDField, ); \
4773 OPTIONAL(thrownTypes, MDField, );
4774 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4775#undef VISIT_MD_FIELDS
4776
4777 // An explicit spFlags field takes precedence over individual fields in
4778 // older IR versions.
4779 DISubprogram::DISPFlags SPFlags =
4780 spFlags.Seen ? spFlags.Val
4781 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4782 isOptimized.Val, virtuality.Val);
4783 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4784 return Lex.Error(
4785 Loc,
4786 "missing 'distinct', required for !DISubprogram that is a Definition");
4787 Result = GET_OR_DISTINCT((IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4788 DISubprogram,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4789 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4790 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4791 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4792 declaration.Val, retainedNodes.Val, thrownTypes.Val))(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
;
4793 return false;
4794}
4795
4796/// parseDILexicalBlock:
4797/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4798bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4799#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4800 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4801 OPTIONAL(file, MDField, ); \
4802 OPTIONAL(line, LineField, ); \
4803 OPTIONAL(column, ColumnField, );
4804 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4805#undef VISIT_MD_FIELDS
4806
4807 Result = GET_OR_DISTINCT((IsDistinct ? DILexicalBlock::getDistinct (Context, scope.Val
, file.Val, line.Val, column.Val) : DILexicalBlock::get (Context
, scope.Val, file.Val, line.Val, column.Val))
4808 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val))(IsDistinct ? DILexicalBlock::getDistinct (Context, scope.Val
, file.Val, line.Val, column.Val) : DILexicalBlock::get (Context
, scope.Val, file.Val, line.Val, column.Val))
;
4809 return false;
4810}
4811
4812/// parseDILexicalBlockFile:
4813/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4814bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4815#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4816 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4817 OPTIONAL(file, MDField, ); \
4818 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX0xffffffffU));
4819 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4820#undef VISIT_MD_FIELDS
4821
4822 Result = GET_OR_DISTINCT(DILexicalBlockFile,(IsDistinct ? DILexicalBlockFile::getDistinct (Context, scope
.Val, file.Val, discriminator.Val) : DILexicalBlockFile::get (
Context, scope.Val, file.Val, discriminator.Val))
4823 (Context, scope.Val, file.Val, discriminator.Val))(IsDistinct ? DILexicalBlockFile::getDistinct (Context, scope
.Val, file.Val, discriminator.Val) : DILexicalBlockFile::get (
Context, scope.Val, file.Val, discriminator.Val))
;
4824 return false;
4825}
4826
4827/// parseDICommonBlock:
4828/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4829bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
4830#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4831 REQUIRED(scope, MDField, ); \
4832 OPTIONAL(declaration, MDField, ); \
4833 OPTIONAL(name, MDStringField, ); \
4834 OPTIONAL(file, MDField, ); \
4835 OPTIONAL(line, LineField, );
4836 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4837#undef VISIT_MD_FIELDS
4838
4839 Result = GET_OR_DISTINCT(DICommonBlock,(IsDistinct ? DICommonBlock::getDistinct (Context, scope.Val,
declaration.Val, name.Val, file.Val, line.Val) : DICommonBlock
::get (Context, scope.Val, declaration.Val, name.Val, file.Val
, line.Val))
4840 (Context, scope.Val, declaration.Val, name.Val,(IsDistinct ? DICommonBlock::getDistinct (Context, scope.Val,
declaration.Val, name.Val, file.Val, line.Val) : DICommonBlock
::get (Context, scope.Val, declaration.Val, name.Val, file.Val
, line.Val))
4841 file.Val, line.Val))(IsDistinct ? DICommonBlock::getDistinct (Context, scope.Val,
declaration.Val, name.Val, file.Val, line.Val) : DICommonBlock
::get (Context, scope.Val, declaration.Val, name.Val, file.Val
, line.Val))
;
4842 return false;
4843}
4844
4845/// parseDINamespace:
4846/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4847bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
4848#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4849 REQUIRED(scope, MDField, ); \
4850 OPTIONAL(name, MDStringField, ); \
4851 OPTIONAL(exportSymbols, MDBoolField, );
4852 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4853#undef VISIT_MD_FIELDS
4854
4855 Result = GET_OR_DISTINCT(DINamespace,(IsDistinct ? DINamespace::getDistinct (Context, scope.Val, name
.Val, exportSymbols.Val) : DINamespace::get (Context, scope.Val
, name.Val, exportSymbols.Val))
4856 (Context, scope.Val, name.Val, exportSymbols.Val))(IsDistinct ? DINamespace::getDistinct (Context, scope.Val, name
.Val, exportSymbols.Val) : DINamespace::get (Context, scope.Val
, name.Val, exportSymbols.Val))
;
4857 return false;
4858}
4859
4860/// parseDIMacro:
4861/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
4862/// "SomeValue")
4863bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
4864#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4865 REQUIRED(type, DwarfMacinfoTypeField, ); \
4866 OPTIONAL(line, LineField, ); \
4867 REQUIRED(name, MDStringField, ); \
4868 OPTIONAL(value, MDStringField, );
4869 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4870#undef VISIT_MD_FIELDS
4871
4872 Result = GET_OR_DISTINCT(DIMacro,(IsDistinct ? DIMacro::getDistinct (Context, type.Val, line.Val
, name.Val, value.Val) : DIMacro::get (Context, type.Val, line
.Val, name.Val, value.Val))
4873 (Context, type.Val, line.Val, name.Val, value.Val))(IsDistinct ? DIMacro::getDistinct (Context, type.Val, line.Val
, name.Val, value.Val) : DIMacro::get (Context, type.Val, line
.Val, name.Val, value.Val))
;
4874 return false;
4875}
4876
4877/// parseDIMacroFile:
4878/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4879bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4880#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4881 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4882 OPTIONAL(line, LineField, ); \
4883 REQUIRED(file, MDField, ); \
4884 OPTIONAL(nodes, MDField, );
4885 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4886#undef VISIT_MD_FIELDS
4887
4888 Result = GET_OR_DISTINCT(DIMacroFile,(IsDistinct ? DIMacroFile::getDistinct (Context, type.Val, line
.Val, file.Val, nodes.Val) : DIMacroFile::get (Context, type.
Val, line.Val, file.Val, nodes.Val))
4889 (Context, type.Val, line.Val, file.Val, nodes.Val))(IsDistinct ? DIMacroFile::getDistinct (Context, type.Val, line
.Val, file.Val, nodes.Val) : DIMacroFile::get (Context, type.
Val, line.Val, file.Val, nodes.Val))
;
4890 return false;
4891}
4892
4893/// parseDIModule:
4894/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
4895/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
4896/// file: !1, line: 4, isDecl: false)
4897bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
4898#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4899 REQUIRED(scope, MDField, ); \
4900 REQUIRED(name, MDStringField, ); \
4901 OPTIONAL(configMacros, MDStringField, ); \
4902 OPTIONAL(includePath, MDStringField, ); \
4903 OPTIONAL(apinotes, MDStringField, ); \
4904 OPTIONAL(file, MDField, ); \
4905 OPTIONAL(line, LineField, ); \
4906 OPTIONAL(isDecl, MDBoolField, );
4907 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4908#undef VISIT_MD_FIELDS
4909
4910 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,(IsDistinct ? DIModule::getDistinct (Context, file.Val, scope
.Val, name.Val, configMacros.Val, includePath.Val, apinotes.Val
, line.Val, isDecl.Val) : DIModule::get (Context, file.Val, scope
.Val, name.Val, configMacros.Val, includePath.Val, apinotes.Val
, line.Val, isDecl.Val))
4911 configMacros.Val, includePath.Val,(IsDistinct ? DIModule::getDistinct (Context, file.Val, scope
.Val, name.Val, configMacros.Val, includePath.Val, apinotes.Val
, line.Val, isDecl.Val) : DIModule::get (Context, file.Val, scope
.Val, name.Val, configMacros.Val, includePath.Val, apinotes.Val
, line.Val, isDecl.Val))
4912 apinotes.Val, line.Val, isDecl.Val))(IsDistinct ? DIModule::getDistinct (Context, file.Val, scope
.Val, name.Val, configMacros.Val, includePath.Val, apinotes.Val
, line.Val, isDecl.Val) : DIModule::get (Context, file.Val, scope
.Val, name.Val, configMacros.Val, includePath.Val, apinotes.Val
, line.Val, isDecl.Val))
;
4913 return false;
4914}
4915
4916/// parseDITemplateTypeParameter:
4917/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
4918bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4919#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4920 OPTIONAL(name, MDStringField, ); \
4921 REQUIRED(type, MDField, ); \
4922 OPTIONAL(defaulted, MDBoolField, );
4923 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4924#undef VISIT_MD_FIELDS
4925
4926 Result = GET_OR_DISTINCT(DITemplateTypeParameter,(IsDistinct ? DITemplateTypeParameter::getDistinct (Context, name
.Val, type.Val, defaulted.Val) : DITemplateTypeParameter::get
(Context, name.Val, type.Val, defaulted.Val))
4927 (Context, name.Val, type.Val, defaulted.Val))(IsDistinct ? DITemplateTypeParameter::getDistinct (Context, name
.Val, type.Val, defaulted.Val) : DITemplateTypeParameter::get
(Context, name.Val, type.Val, defaulted.Val))
;
4928 return false;
4929}
4930
4931/// parseDITemplateValueParameter:
4932/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4933/// name: "V", type: !1, defaulted: false,
4934/// value: i32 7)
4935bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4936#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4937 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4938 OPTIONAL(name, MDStringField, ); \
4939 OPTIONAL(type, MDField, ); \
4940 OPTIONAL(defaulted, MDBoolField, ); \
4941 REQUIRED(value, MDField, );
4942
4943 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4944#undef VISIT_MD_FIELDS
4945
4946 Result = GET_OR_DISTINCT((IsDistinct ? DITemplateValueParameter::getDistinct (Context,
tag.Val, name.Val, type.Val, defaulted.Val, value.Val) : DITemplateValueParameter
::get (Context, tag.Val, name.Val, type.Val, defaulted.Val, value
.Val))
4947 DITemplateValueParameter,(IsDistinct ? DITemplateValueParameter::getDistinct (Context,
tag.Val, name.Val, type.Val, defaulted.Val, value.Val) : DITemplateValueParameter
::get (Context, tag.Val, name.Val, type.Val, defaulted.Val, value
.Val))
4948 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val))(IsDistinct ? DITemplateValueParameter::getDistinct (Context,
tag.Val, name.Val, type.Val, defaulted.Val, value.Val) : DITemplateValueParameter
::get (Context, tag.Val, name.Val, type.Val, defaulted.Val, value
.Val))
;
4949 return false;
4950}
4951
4952/// parseDIGlobalVariable:
4953/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4954/// file: !1, line: 7, type: !2, isLocal: false,
4955/// isDefinition: true, templateParams: !3,
4956/// declaration: !4, align: 8)
4957bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4958#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4959 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4960 OPTIONAL(scope, MDField, ); \
4961 OPTIONAL(linkageName, MDStringField, ); \
4962 OPTIONAL(file, MDField, ); \
4963 OPTIONAL(line, LineField, ); \
4964 OPTIONAL(type, MDField, ); \
4965 OPTIONAL(isLocal, MDBoolField, ); \
4966 OPTIONAL(isDefinition, MDBoolField, (true)); \
4967 OPTIONAL(templateParams, MDField, ); \
4968 OPTIONAL(declaration, MDField, ); \
4969 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX0xffffffffU));
4970 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4971#undef VISIT_MD_FIELDS
4972
4973 Result =
4974 GET_OR_DISTINCT(DIGlobalVariable,(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
4975 (Context, scope.Val, name.Val, linkageName.Val, file.Val,(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
4976 line.Val, type.Val, isLocal.Val, isDefinition.Val,(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
4977 declaration.Val, templateParams.Val, align.Val))(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
;
4978 return false;
4979}
4980
4981/// parseDILocalVariable:
4982/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4983/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4984/// align: 8)
4985/// ::= !DILocalVariable(scope: !0, name: "foo",
4986/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4987/// align: 8)
4988bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4989#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4990 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4991 OPTIONAL(name, MDStringField, ); \
4992 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX0xffff)); \
4993 OPTIONAL(file, MDField, ); \
4994 OPTIONAL(line, LineField, ); \
4995 OPTIONAL(type, MDField, ); \
4996 OPTIONAL(flags, DIFlagField, ); \
4997 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX0xffffffffU));
4998 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4999#undef VISIT_MD_FIELDS
5000
5001 Result = GET_OR_DISTINCT(DILocalVariable,(IsDistinct ? DILocalVariable::getDistinct (Context, scope.Val
, name.Val, file.Val, line.Val, type.Val, arg.Val, flags.Val,
align.Val) : DILocalVariable::get (Context, scope.Val, name.
Val, file.Val, line.Val, type.Val, arg.Val, flags.Val, align.
Val))
5002 (Context, scope.Val, name.Val, file.Val, line.Val,(IsDistinct ? DILocalVariable::getDistinct (Context, scope.Val
, name.Val, file.Val, line.Val, type.Val, arg.Val, flags.Val,
align.Val) : DILocalVariable::get (Context, scope.Val, name.
Val, file.Val, line.Val, type.Val, arg.Val, flags.Val, align.
Val))
5003 type.Val, arg.Val, flags.Val, align.Val))(IsDistinct ? DILocalVariable::getDistinct (Context, scope.Val
, name.Val, file.Val, line.Val, type.Val, arg.Val, flags.Val,
align.Val) : DILocalVariable::get (Context, scope.Val, name.
Val, file.Val, line.Val, type.Val, arg.Val, flags.Val, align.
Val))
;
5004 return false;
5005}
5006
5007/// parseDILabel:
5008/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5009bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5010#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5011 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5012 REQUIRED(name, MDStringField, ); \
5013 REQUIRED(file, MDField, ); \
5014 REQUIRED(line, LineField, );
5015 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
5016#undef VISIT_MD_FIELDS
5017
5018 Result = GET_OR_DISTINCT(DILabel,(IsDistinct ? DILabel::getDistinct (Context, scope.Val, name.
Val, file.Val, line.Val) : DILabel::get (Context, scope.Val, name
.Val, file.Val, line.Val))
5019 (Context, scope.Val, name.Val, file.Val, line.Val))(IsDistinct ? DILabel::getDistinct (Context, scope.Val, name.
Val, file.Val, line.Val) : DILabel::get (Context, scope.Val, name
.Val, file.Val, line.Val))
;
5020 return false;
5021}
5022
5023/// parseDIExpression:
5024/// ::= !DIExpression(0, 7, -1)
5025bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5026 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((void)0);
5027 Lex.Lex();
5028
5029 if (parseToken(lltok::lparen, "expected '(' here"))
5030 return true;
5031
5032 SmallVector<uint64_t, 8> Elements;
5033 if (Lex.getKind() != lltok::rparen)
5034 do {
5035 if (Lex.getKind() == lltok::DwarfOp) {
5036 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5037 Lex.Lex();
5038 Elements.push_back(Op);
5039 continue;
5040 }
5041 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5042 }
5043
5044 if (Lex.getKind() == lltok::DwarfAttEncoding) {
5045 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5046 Lex.Lex();
5047 Elements.push_back(Op);
5048 continue;
5049 }
5050 return tokError(Twine("invalid DWARF attribute encoding '") +
5051 Lex.getStrVal() + "'");
5052 }
5053
5054 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5055 return tokError("expected unsigned integer");
5056
5057 auto &U = Lex.getAPSIntVal();
5058 if (U.ugt(UINT64_MAX0xffffffffffffffffULL))
5059 return tokError("element too large, limit is " + Twine(UINT64_MAX0xffffffffffffffffULL));
5060 Elements.push_back(U.getZExtValue());
5061 Lex.Lex();
5062 } while (EatIfPresent(lltok::comma));
5063
5064 if (parseToken(lltok::rparen, "expected ')' here"))
5065 return true;
5066
5067 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements))(IsDistinct ? DIExpression::getDistinct (Context, Elements) :
DIExpression::get (Context, Elements))
;
5068 return false;
5069}
5070
5071bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) {
5072 return parseDIArgList(Result, IsDistinct, nullptr);
5073}
5074/// ParseDIArgList:
5075/// ::= !DIArgList(i32 7, i64 %0)
5076bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct,
5077 PerFunctionState *PFS) {
5078 assert(PFS && "Expected valid function state")((void)0);
5079 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((void)0);
5080 Lex.Lex();
5081
5082 if (parseToken(lltok::lparen, "expected '(' here"))
5083 return true;
5084
5085 SmallVector<ValueAsMetadata *, 4> Args;
5086 if (Lex.getKind() != lltok::rparen)
5087 do {
5088 Metadata *MD;
5089 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5090 return true;
5091 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5092 } while (EatIfPresent(lltok::comma));
5093
5094 if (parseToken(lltok::rparen, "expected ')' here"))
5095 return true;
5096
5097 Result = GET_OR_DISTINCT(DIArgList, (Context, Args))(IsDistinct ? DIArgList::getDistinct (Context, Args) : DIArgList
::get (Context, Args))
;
5098 return false;
5099}
5100
5101/// parseDIGlobalVariableExpression:
5102/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5103bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5104 bool IsDistinct) {
5105#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5106 REQUIRED(var, MDField, ); \
5107 REQUIRED(expr, MDField, );
5108 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
5109#undef VISIT_MD_FIELDS
5110
5111 Result =
5112 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val))(IsDistinct ? DIGlobalVariableExpression::getDistinct (Context
, var.Val, expr.Val) : DIGlobalVariableExpression::get (Context
, var.Val, expr.Val))
;
5113 return false;
5114}
5115
5116/// parseDIObjCProperty:
5117/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5118/// getter: "getFoo", attributes: 7, type: !2)
5119bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5120#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5121 OPTIONAL(name, MDStringField, ); \
5122 OPTIONAL(file, MDField, ); \
5123 OPTIONAL(line, LineField, ); \
5124 OPTIONAL(setter, MDStringField, ); \
5125 OPTIONAL(getter, MDStringField, ); \
5126 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX0xffffffffU)); \
5127 OPTIONAL(type, MDField, );
5128 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
5129#undef VISIT_MD_FIELDS
5130
5131 Result = GET_OR_DISTINCT(DIObjCProperty,(IsDistinct ? DIObjCProperty::getDistinct (Context, name.Val,
file.Val, line.Val, setter.Val, getter.Val, attributes.Val, type
.Val) : DIObjCProperty::get (Context, name.Val, file.Val, line
.Val, setter.Val, getter.Val, attributes.Val, type.Val))
5132 (Context, name.Val, file.Val, line.Val, setter.Val,(IsDistinct ? DIObjCProperty::getDistinct (Context, name.Val,
file.Val, line.Val, setter.Val, getter.Val, attributes.Val, type
.Val) : DIObjCProperty::get (Context, name.Val, file.Val, line
.Val, setter.Val, getter.Val, attributes.Val, type.Val))
5133 getter.Val, attributes.Val, type.Val))(IsDistinct ? DIObjCProperty::getDistinct (Context, name.Val,
file.Val, line.Val, setter.Val, getter.Val, attributes.Val, type
.Val) : DIObjCProperty::get (Context, name.Val, file.Val, line
.Val, setter.Val, getter.Val, attributes.Val, type.Val))
;
5134 return false;
5135}
5136
5137/// parseDIImportedEntity:
5138/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5139/// line: 7, name: "foo")
5140bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5141#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5142 REQUIRED(tag, DwarfTagField, ); \
5143 REQUIRED(scope, MDField, ); \
5144 OPTIONAL(entity, MDField, ); \
5145 OPTIONAL(file, MDField, ); \
5146 OPTIONAL(line, LineField, ); \
5147 OPTIONAL(name, MDStringField, );
5148 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (parseMDFieldsImpl( [&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return tokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
5149#undef VISIT_MD_FIELDS
5150
5151 Result = GET_OR_DISTINCT((IsDistinct ? DIImportedEntity::getDistinct (Context, tag.Val
, scope.Val, entity.Val, file.Val, line.Val, name.Val) : DIImportedEntity
::get (Context, tag.Val, scope.Val, entity.Val, file.Val, line
.Val, name.Val))
5152 DIImportedEntity,(IsDistinct ? DIImportedEntity::getDistinct (Context, tag.Val
, scope.Val, entity.Val, file.Val, line.Val, name.Val) : DIImportedEntity
::get (Context, tag.Val, scope.Val, entity.Val, file.Val, line
.Val, name.Val))
5153 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val))(IsDistinct ? DIImportedEntity::getDistinct (Context, tag.Val
, scope.Val, entity.Val, file.Val, line.Val, name.Val) : DIImportedEntity
::get (Context, tag.Val, scope.Val, entity.Val, file.Val, line
.Val, name.Val))
;
5154 return false;
5155}
5156
5157#undef PARSE_MD_FIELD
5158#undef NOP_FIELD
5159#undef REQUIRE_FIELD
5160#undef DECLARE_FIELD
5161
5162/// parseMetadataAsValue
5163/// ::= metadata i32 %local
5164/// ::= metadata i32 @global
5165/// ::= metadata i32 7
5166/// ::= metadata !0
5167/// ::= metadata !{...}
5168/// ::= metadata !"string"
5169bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5170 // Note: the type 'metadata' has already been parsed.
5171 Metadata *MD;
5172 if (parseMetadata(MD, &PFS))
5173 return true;
5174
5175 V = MetadataAsValue::get(Context, MD);
5176 return false;
5177}
5178
5179/// parseValueAsMetadata
5180/// ::= i32 %local
5181/// ::= i32 @global
5182/// ::= i32 7
5183bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5184 PerFunctionState *PFS) {
5185 Type *Ty;
5186 LocTy Loc;
5187 if (parseType(Ty, TypeMsg, Loc))
5188 return true;
5189 if (Ty->isMetadataTy())
5190 return error(Loc, "invalid metadata-value-metadata roundtrip");
5191
5192 Value *V;
5193 if (parseValue(Ty, V, PFS))
5194 return true;
5195
5196 MD = ValueAsMetadata::get(V);
5197 return false;
5198}
5199
5200/// parseMetadata
5201/// ::= i32 %local
5202/// ::= i32 @global
5203/// ::= i32 7
5204/// ::= !42
5205/// ::= !{...}
5206/// ::= !"string"
5207/// ::= !DILocation(...)
5208bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5209 if (Lex.getKind() == lltok::MetadataVar) {
5210 MDNode *N;
5211 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5212 // so parsing this requires a Function State.
5213 if (Lex.getStrVal() == "DIArgList") {
5214 if (parseDIArgList(N, false, PFS))
5215 return true;
5216 } else if (parseSpecializedMDNode(N)) {
5217 return true;
5218 }
5219 MD = N;
5220 return false;
5221 }
5222
5223 // ValueAsMetadata:
5224 // <type> <value>
5225 if (Lex.getKind() != lltok::exclaim)
5226 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
5227
5228 // '!'.
5229 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here")((void)0);
5230 Lex.Lex();
5231
5232 // MDString:
5233 // ::= '!' STRINGCONSTANT
5234 if (Lex.getKind() == lltok::StringConstant) {
5235 MDString *S;
5236 if (parseMDString(S))
5237 return true;
5238 MD = S;
5239 return false;
5240 }
5241
5242 // MDNode:
5243 // !{ ... }
5244 // !7
5245 MDNode *N;
5246 if (parseMDNodeTail(N))
5247 return true;
5248 MD = N;
5249 return false;
5250}
5251
5252//===----------------------------------------------------------------------===//
5253// Function Parsing.
5254//===----------------------------------------------------------------------===//
5255
5256bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5257 PerFunctionState *PFS, bool IsCall) {
5258 if (Ty->isFunctionTy())
5259 return error(ID.Loc, "functions are not values, refer to them as pointers");
5260
5261 switch (ID.Kind) {
5262 case ValID::t_LocalID:
5263 if (!PFS)
5264 return error(ID.Loc, "invalid use of function-local name");
5265 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5266 return V == nullptr;
5267 case ValID::t_LocalName:
5268 if (!PFS)
5269 return error(ID.Loc, "invalid use of function-local name");
5270 V = PFS->getVal(ID.StrVal, Ty, ID.Loc, IsCall);
5271 return V == nullptr;
5272 case ValID::t_InlineAsm: {
5273 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5274 return error(ID.Loc, "invalid type for inline asm constraint string");
5275 V = InlineAsm::get(
5276 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
5277 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
5278 return false;
5279 }
5280 case ValID::t_GlobalName:
5281 V = getGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
5282 return V == nullptr;
5283 case ValID::t_GlobalID:
5284 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5285 return V == nullptr;
5286 case ValID::t_APSInt:
5287 if (!Ty->isIntegerTy())
5288 return error(ID.Loc, "integer constant must have integer type");
5289 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5290 V = ConstantInt::get(Context, ID.APSIntVal);
5291 return false;
5292 case ValID::t_APFloat:
5293 if (!Ty->isFloatingPointTy() ||
5294 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5295 return error(ID.Loc, "floating point constant invalid for type");
5296
5297 // The lexer has no type info, so builds all half, bfloat, float, and double
5298 // FP constants as double. Fix this here. Long double does not need this.
5299 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5300 // Check for signaling before potentially converting and losing that info.
5301 bool IsSNAN = ID.APFloatVal.isSignaling();
5302 bool Ignored;
5303 if (Ty->isHalfTy())
5304 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5305 &Ignored);
5306 else if (Ty->isBFloatTy())
5307 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
5308 &Ignored);
5309 else if (Ty->isFloatTy())
5310 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5311 &Ignored);
5312 if (IsSNAN) {
5313 // The convert call above may quiet an SNaN, so manufacture another
5314 // SNaN. The bitcast works because the payload (significand) parameter
5315 // is truncated to fit.
5316 APInt Payload = ID.APFloatVal.bitcastToAPInt();
5317 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
5318 ID.APFloatVal.isNegative(), &Payload);
5319 }
5320 }
5321 V = ConstantFP::get(Context, ID.APFloatVal);
5322
5323 if (V->getType() != Ty)
5324 return error(ID.Loc, "floating point constant does not have type '" +
5325 getTypeString(Ty) + "'");
5326
5327 return false;
5328 case ValID::t_Null:
5329 if (!Ty->isPointerTy())
5330 return error(ID.Loc, "null must be a pointer type");
5331 V = ConstantPointerNull::get(cast<PointerType>(Ty));
5332 return false;
5333 case ValID::t_Undef:
5334 // FIXME: LabelTy should not be a first-class type.
5335 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5336 return error(ID.Loc, "invalid type for undef constant");
5337 V = UndefValue::get(Ty);
5338 return false;
5339 case ValID::t_EmptyArray:
5340 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5341 return error(ID.Loc, "invalid empty array initializer");
5342 V = UndefValue::get(Ty);
5343 return false;
5344 case ValID::t_Zero:
5345 // FIXME: LabelTy should not be a first-class type.
5346 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5347 return error(ID.Loc, "invalid type for null constant");
5348 V = Constant::getNullValue(Ty);
5349 return false;
5350 case ValID::t_None:
5351 if (!Ty->isTokenTy())
5352 return error(ID.Loc, "invalid type for none constant");
5353 V = Constant::getNullValue(Ty);
5354 return false;
5355 case ValID::t_Poison:
5356 // FIXME: LabelTy should not be a first-class type.
5357 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5358 return error(ID.Loc, "invalid type for poison constant");
5359 V = PoisonValue::get(Ty);
5360 return false;
5361 case ValID::t_Constant:
5362 if (ID.ConstantVal->getType() != Ty)
5363 return error(ID.Loc, "constant expression type mismatch: got type '" +
5364 getTypeString(ID.ConstantVal->getType()) +
5365 "' but expected '" + getTypeString(Ty) + "'");
5366 V = ID.ConstantVal;
5367 return false;
5368 case ValID::t_ConstantStruct:
5369 case ValID::t_PackedConstantStruct:
5370 if (StructType *ST = dyn_cast<StructType>(Ty)) {
5371 if (ST->getNumElements() != ID.UIntVal)
5372 return error(ID.Loc,
5373 "initializer with struct type has wrong # elements");
5374 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5375 return error(ID.Loc, "packed'ness of initializer and type don't match");
5376
5377 // Verify that the elements are compatible with the structtype.
5378 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5379 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5380 return error(
5381 ID.Loc,
5382 "element " + Twine(i) +
5383 " of struct initializer doesn't match struct element type");
5384
5385 V = ConstantStruct::get(
5386 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5387 } else
5388 return error(ID.Loc, "constant expression type mismatch");
5389 return false;
5390 }
5391 llvm_unreachable("Invalid ValID")__builtin_unreachable();
5392}
5393
5394bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5395 C = nullptr;
5396 ValID ID;
5397 auto Loc = Lex.getLoc();
5398 if (parseValID(ID, /*PFS=*/nullptr))
5399 return true;
5400 switch (ID.Kind) {
5401 case ValID::t_APSInt:
5402 case ValID::t_APFloat:
5403 case ValID::t_Undef:
5404 case ValID::t_Constant:
5405 case ValID::t_ConstantStruct:
5406 case ValID::t_PackedConstantStruct: {
5407 Value *V;
5408 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
5409 return true;
5410 assert(isa<Constant>(V) && "Expected a constant value")((void)0);
5411 C = cast<Constant>(V);
5412 return false;
5413 }
5414 case ValID::t_Null:
5415 C = Constant::getNullValue(Ty);
5416 return false;
5417 default:
5418 return error(Loc, "expected a constant value");
5419 }
5420}
5421
5422bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5423 V = nullptr;
5424 ValID ID;
5425 return parseValID(ID, PFS, Ty) ||
5426 convertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
5427}
5428
5429bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5430 Type *Ty = nullptr;
5431 return parseType(Ty) || parseValue(Ty, V, PFS);
5432}
5433
5434bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5435 PerFunctionState &PFS) {
5436 Value *V;
5437 Loc = Lex.getLoc();
5438 if (parseTypeAndValue(V, PFS))
5439 return true;
5440 if (!isa<BasicBlock>(V))
5441 return error(Loc, "expected a basic block");
5442 BB = cast<BasicBlock>(V);
5443 return false;
5444}
5445
5446/// FunctionHeader
5447/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5448/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5449/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5450/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5451bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) {
5452 // parse the linkage.
5453 LocTy LinkageLoc = Lex.getLoc();
5454 unsigned Linkage;
5455 unsigned Visibility;
5456 unsigned DLLStorageClass;
5457 bool DSOLocal;
5458 AttrBuilder RetAttrs;
5459 unsigned CC;
5460 bool HasLinkage;
5461 Type *RetType = nullptr;
5462 LocTy RetTypeLoc = Lex.getLoc();
5463 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5464 DSOLocal) ||
5465 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
5466 parseType(RetType, RetTypeLoc, true /*void allowed*/))
5467 return true;
5468
5469 // Verify that the linkage is ok.
5470 switch ((GlobalValue::LinkageTypes)Linkage) {
5471 case GlobalValue::ExternalLinkage:
5472 break; // always ok.
5473 case GlobalValue::ExternalWeakLinkage:
5474 if (IsDefine)
5475 return error(LinkageLoc, "invalid linkage for function definition");
5476 break;
5477 case GlobalValue::PrivateLinkage:
5478 case GlobalValue::InternalLinkage:
5479 case GlobalValue::AvailableExternallyLinkage:
5480 case GlobalValue::LinkOnceAnyLinkage:
5481 case GlobalValue::LinkOnceODRLinkage:
5482 case GlobalValue::WeakAnyLinkage:
5483 case GlobalValue::WeakODRLinkage:
5484 if (!IsDefine)
5485 return error(LinkageLoc, "invalid linkage for function declaration");
5486 break;
5487 case GlobalValue::AppendingLinkage:
5488 case GlobalValue::CommonLinkage:
5489 return error(LinkageLoc, "invalid function linkage type");
5490 }
5491
5492 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5493 return error(LinkageLoc,
5494 "symbol with local linkage must have default visibility");
5495
5496 if (!FunctionType::isValidReturnType(RetType))
5497 return error(RetTypeLoc, "invalid function return type");
5498
5499 LocTy NameLoc = Lex.getLoc();
5500
5501 std::string FunctionName;
5502 if (Lex.getKind() == lltok::GlobalVar) {
5503 FunctionName = Lex.getStrVal();
5504 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5505 unsigned NameID = Lex.getUIntVal();
5506
5507 if (NameID != NumberedVals.size())
5508 return tokError("function expected to be numbered '%" +
5509 Twine(NumberedVals.size()) + "'");
5510 } else {
5511 return tokError("expected function name");
5512 }
5513
5514 Lex.Lex();
5515
5516 if (Lex.getKind() != lltok::lparen)
5517 return tokError("expected '(' in function argument list");
5518
5519 SmallVector<ArgInfo, 8> ArgList;
5520 bool IsVarArg;
5521 AttrBuilder FuncAttrs;
5522 std::vector<unsigned> FwdRefAttrGrps;
5523 LocTy BuiltinLoc;
5524 std::string Section;
5525 std::string Partition;
5526 MaybeAlign Alignment;
5527 std::string GC;
5528 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5529 unsigned AddrSpace = 0;
5530 Constant *Prefix = nullptr;
5531 Constant *Prologue = nullptr;
5532 Constant *PersonalityFn = nullptr;
5533 Comdat *C;
5534
5535 if (parseArgumentList(ArgList, IsVarArg) ||
5536 parseOptionalUnnamedAddr(UnnamedAddr) ||
5537 parseOptionalProgramAddrSpace(AddrSpace) ||
5538 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5539 BuiltinLoc) ||
5540 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
5541 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
5542 parseOptionalComdat(FunctionName, C) ||
5543 parseOptionalAlignment(Alignment) ||
5544 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
5545 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
5546 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
5547 (EatIfPresent(lltok::kw_personality) &&
5548 parseGlobalTypeAndValue(PersonalityFn)))
5549 return true;
5550
5551 if (FuncAttrs.contains(Attribute::Builtin))
5552 return error(BuiltinLoc, "'builtin' attribute not valid on function");
5553
5554 // If the alignment was parsed as an attribute, move to the alignment field.
5555 if (FuncAttrs.hasAlignmentAttr()) {
5556 Alignment = FuncAttrs.getAlignment();
5557 FuncAttrs.removeAttribute(Attribute::Alignment);
5558 }
5559
5560 // Okay, if we got here, the function is syntactically valid. Convert types
5561 // and do semantic checks.
5562 std::vector<Type*> ParamTypeList;
5563 SmallVector<AttributeSet, 8> Attrs;
5564
5565 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5566 ParamTypeList.push_back(ArgList[i].Ty);
5567 Attrs.push_back(ArgList[i].Attrs);
5568 }
5569
5570 AttributeList PAL =
5571 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5572 AttributeSet::get(Context, RetAttrs), Attrs);
5573
5574 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
5575 return error(RetTypeLoc, "functions with 'sret' argument must return void");
5576
5577 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
5578 PointerType *PFT = PointerType::get(FT, AddrSpace);
5579
5580 Fn = nullptr;
5581 GlobalValue *FwdFn = nullptr;
5582 if (!FunctionName.empty()) {
5583 // If this was a definition of a forward reference, remove the definition
5584 // from the forward reference table and fill in the forward ref.
5585 auto FRVI = ForwardRefVals.find(FunctionName);
5586 if (FRVI != ForwardRefVals.end()) {
5587 FwdFn = FRVI->second.first;
5588 if (!FwdFn->getType()->isOpaque()) {
5589 if (!FwdFn->getType()->getPointerElementType()->isFunctionTy())
5590 return error(FRVI->second.second, "invalid forward reference to "
5591 "function as global value!");
5592 if (FwdFn->getType() != PFT)
5593 return error(FRVI->second.second,
5594 "invalid forward reference to "
5595 "function '" +
5596 FunctionName +
5597 "' with wrong type: "
5598 "expected '" +
5599 getTypeString(PFT) + "' but was '" +
5600 getTypeString(FwdFn->getType()) + "'");
5601 }
5602 ForwardRefVals.erase(FRVI);
5603 } else if ((Fn = M->getFunction(FunctionName))) {
5604 // Reject redefinitions.
5605 return error(NameLoc,
5606 "invalid redefinition of function '" + FunctionName + "'");
5607 } else if (M->getNamedValue(FunctionName)) {
5608 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5609 }
5610
5611 } else {
5612 // If this is a definition of a forward referenced function, make sure the
5613 // types agree.
5614 auto I = ForwardRefValIDs.find(NumberedVals.size());
5615 if (I != ForwardRefValIDs.end()) {
5616 FwdFn = cast<Function>(I->second.first);
5617 if (!FwdFn->getType()->isOpaque() && FwdFn->getType() != PFT)
5618 return error(NameLoc, "type of definition and forward reference of '@" +
5619 Twine(NumberedVals.size()) +
5620 "' disagree: "
5621 "expected '" +
5622 getTypeString(PFT) + "' but was '" +
5623 getTypeString(FwdFn->getType()) + "'");
5624 ForwardRefValIDs.erase(I);
5625 }
5626 }
5627
5628 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5629 FunctionName, M);
5630
5631 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS")((void)0);
5632
5633 if (FunctionName.empty())
5634 NumberedVals.push_back(Fn);
5635
5636 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5637 maybeSetDSOLocal(DSOLocal, *Fn);
5638 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5639 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5640 Fn->setCallingConv(CC);
5641 Fn->setAttributes(PAL);
5642 Fn->setUnnamedAddr(UnnamedAddr);
5643 Fn->setAlignment(MaybeAlign(Alignment));
5644 Fn->setSection(Section);
5645 Fn->setPartition(Partition);
5646 Fn->setComdat(C);
5647 Fn->setPersonalityFn(PersonalityFn);
5648 if (!GC.empty()) Fn->setGC(GC);
5649 Fn->setPrefixData(Prefix);
5650 Fn->setPrologueData(Prologue);
5651 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5652
5653 // Add all of the arguments we parsed to the function.
5654 Function::arg_iterator ArgIt = Fn->arg_begin();
5655 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5656 // If the argument has a name, insert it into the argument symbol table.
5657 if (ArgList[i].Name.empty()) continue;
5658
5659 // Set the name, if it conflicted, it will be auto-renamed.
5660 ArgIt->setName(ArgList[i].Name);
5661
5662 if (ArgIt->getName() != ArgList[i].Name)
5663 return error(ArgList[i].Loc,
5664 "redefinition of argument '%" + ArgList[i].Name + "'");
5665 }
5666
5667 if (FwdFn) {
5668 FwdFn->replaceAllUsesWith(Fn);
5669 FwdFn->eraseFromParent();
5670 }
5671
5672 if (IsDefine)
5673 return false;
5674
5675 // Check the declaration has no block address forward references.
5676 ValID ID;
5677 if (FunctionName.empty()) {
5678 ID.Kind = ValID::t_GlobalID;
5679 ID.UIntVal = NumberedVals.size() - 1;
5680 } else {
5681 ID.Kind = ValID::t_GlobalName;
5682 ID.StrVal = FunctionName;
5683 }
5684 auto Blocks = ForwardRefBlockAddresses.find(ID);
5685 if (Blocks != ForwardRefBlockAddresses.end())
5686 return error(Blocks->first.Loc,
5687 "cannot take blockaddress inside a declaration");
5688 return false;
5689}
5690
5691bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5692 ValID ID;
5693 if (FunctionNumber == -1) {
5694 ID.Kind = ValID::t_GlobalName;
5695 ID.StrVal = std::string(F.getName());
5696 } else {
5697 ID.Kind = ValID::t_GlobalID;
5698 ID.UIntVal = FunctionNumber;
5699 }
5700
5701 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5702 if (Blocks == P.ForwardRefBlockAddresses.end())
5703 return false;
5704
5705 for (const auto &I : Blocks->second) {
5706 const ValID &BBID = I.first;
5707 GlobalValue *GV = I.second;
5708
5709 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&((void)0)
5710 "Expected local id or name")((void)0);
5711 BasicBlock *BB;
5712 if (BBID.Kind == ValID::t_LocalName)
5713 BB = getBB(BBID.StrVal, BBID.Loc);
5714 else
5715 BB = getBB(BBID.UIntVal, BBID.Loc);
5716 if (!BB)
5717 return P.error(BBID.Loc, "referenced value is not a basic block");
5718
5719 Value *ResolvedVal = BlockAddress::get(&F, BB);
5720 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
5721 ResolvedVal, false);
5722 if (!ResolvedVal)
5723 return true;
5724 GV->replaceAllUsesWith(ResolvedVal);
5725 GV->eraseFromParent();
5726 }
5727
5728 P.ForwardRefBlockAddresses.erase(Blocks);
5729 return false;
5730}
5731
5732/// parseFunctionBody
5733/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5734bool LLParser::parseFunctionBody(Function &Fn) {
5735 if (Lex.getKind() != lltok::lbrace)
5736 return tokError("expected '{' in function body");
5737 Lex.Lex(); // eat the {.
5738
5739 int FunctionNumber = -1;
5740 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5741
5742 PerFunctionState PFS(*this, Fn, FunctionNumber);
5743
5744 // Resolve block addresses and allow basic blocks to be forward-declared
5745 // within this function.
5746 if (PFS.resolveForwardRefBlockAddresses())
5747 return true;
5748 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5749
5750 // We need at least one basic block.
5751 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5752 return tokError("function body requires at least one basic block");
5753
5754 while (Lex.getKind() != lltok::rbrace &&
5755 Lex.getKind() != lltok::kw_uselistorder)
5756 if (parseBasicBlock(PFS))
5757 return true;
5758
5759 while (Lex.getKind() != lltok::rbrace)
5760 if (parseUseListOrder(&PFS))
5761 return true;
5762
5763 // Eat the }.
5764 Lex.Lex();
5765
5766 // Verify function is ok.
5767 return PFS.finishFunction();
5768}
5769
5770/// parseBasicBlock
5771/// ::= (LabelStr|LabelID)? Instruction*
5772bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
5773 // If this basic block starts out with a name, remember it.
5774 std::string Name;
5775 int NameID = -1;
5776 LocTy NameLoc = Lex.getLoc();
5777 if (Lex.getKind() == lltok::LabelStr) {
5778 Name = Lex.getStrVal();
5779 Lex.Lex();
5780 } else if (Lex.getKind() == lltok::LabelID) {
5781 NameID = Lex.getUIntVal();
5782 Lex.Lex();
5783 }
5784
5785 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
5786 if (!BB)
5787 return true;
5788
5789 std::string NameStr;
5790
5791 // parse the instructions in this block until we get a terminator.
5792 Instruction *Inst;
5793 do {
5794 // This instruction may have three possibilities for a name: a) none
5795 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5796 LocTy NameLoc = Lex.getLoc();
5797 int NameID = -1;
5798 NameStr = "";
5799
5800 if (Lex.getKind() == lltok::LocalVarID) {
5801 NameID = Lex.getUIntVal();
5802 Lex.Lex();
5803 if (parseToken(lltok::equal, "expected '=' after instruction id"))
5804 return true;
5805 } else if (Lex.getKind() == lltok::LocalVar) {
5806 NameStr = Lex.getStrVal();
5807 Lex.Lex();
5808 if (parseToken(lltok::equal, "expected '=' after instruction name"))
5809 return true;
5810 }
5811
5812 switch (parseInstruction(Inst, BB, PFS)) {
5813 default:
5814 llvm_unreachable("Unknown parseInstruction result!")__builtin_unreachable();
5815 case InstError: return true;
5816 case InstNormal:
5817 BB->getInstList().push_back(Inst);
5818
5819 // With a normal result, we check to see if the instruction is followed by
5820 // a comma and metadata.
5821 if (EatIfPresent(lltok::comma))
5822 if (parseInstructionMetadata(*Inst))
5823 return true;
5824 break;
5825 case InstExtraComma:
5826 BB->getInstList().push_back(Inst);
5827
5828 // If the instruction parser ate an extra comma at the end of it, it
5829 // *must* be followed by metadata.
5830 if (parseInstructionMetadata(*Inst))
5831 return true;
5832 break;
5833 }
5834
5835 // Set the name on the instruction.
5836 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
5837 return true;
5838 } while (!Inst->isTerminator());
5839
5840 return false;
5841}
5842
5843//===----------------------------------------------------------------------===//
5844// Instruction Parsing.
5845//===----------------------------------------------------------------------===//
5846
5847/// parseInstruction - parse one of the many different instructions.
5848///
5849int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
5850 PerFunctionState &PFS) {
5851 lltok::Kind Token = Lex.getKind();
5852 if (Token == lltok::Eof)
5853 return tokError("found end of file when expecting more instructions");
5854 LocTy Loc = Lex.getLoc();
5855 unsigned KeywordVal = Lex.getUIntVal();
5856 Lex.Lex(); // Eat the keyword.
5857
5858 switch (Token) {
5859 default:
5860 return error(Loc, "expected instruction opcode");
5861 // Terminator Instructions.
5862 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5863 case lltok::kw_ret:
5864 return parseRet(Inst, BB, PFS);
5865 case lltok::kw_br:
5866 return parseBr(Inst, PFS);
5867 case lltok::kw_switch:
5868 return parseSwitch(Inst, PFS);
5869 case lltok::kw_indirectbr:
5870 return parseIndirectBr(Inst, PFS);
5871 case lltok::kw_invoke:
5872 return parseInvoke(Inst, PFS);
5873 case lltok::kw_resume:
5874 return parseResume(Inst, PFS);
5875 case lltok::kw_cleanupret:
5876 return parseCleanupRet(Inst, PFS);
5877 case lltok::kw_catchret:
5878 return parseCatchRet(Inst, PFS);
5879 case lltok::kw_catchswitch:
5880 return parseCatchSwitch(Inst, PFS);
5881 case lltok::kw_catchpad:
5882 return parseCatchPad(Inst, PFS);
5883 case lltok::kw_cleanuppad:
5884 return parseCleanupPad(Inst, PFS);
5885 case lltok::kw_callbr:
5886 return parseCallBr(Inst, PFS);
5887 // Unary Operators.
5888 case lltok::kw_fneg: {
5889 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5890 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
5891 if (Res != 0)
5892 return Res;
5893 if (FMF.any())
5894 Inst->setFastMathFlags(FMF);
5895 return false;
5896 }
5897 // Binary Operators.
5898 case lltok::kw_add:
5899 case lltok::kw_sub:
5900 case lltok::kw_mul:
5901 case lltok::kw_shl: {
5902 bool NUW = EatIfPresent(lltok::kw_nuw);
5903 bool NSW = EatIfPresent(lltok::kw_nsw);
5904 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5905
5906 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
5907 return true;
5908
5909 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5910 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5911 return false;
5912 }
5913 case lltok::kw_fadd:
5914 case lltok::kw_fsub:
5915 case lltok::kw_fmul:
5916 case lltok::kw_fdiv:
5917 case lltok::kw_frem: {
5918 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5919 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
5920 if (Res != 0)
5921 return Res;
5922 if (FMF.any())
5923 Inst->setFastMathFlags(FMF);
5924 return 0;
5925 }
5926
5927 case lltok::kw_sdiv:
5928 case lltok::kw_udiv:
5929 case lltok::kw_lshr:
5930 case lltok::kw_ashr: {
5931 bool Exact = EatIfPresent(lltok::kw_exact);
5932
5933 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
5934 return true;
5935 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5936 return false;
5937 }
5938
5939 case lltok::kw_urem:
5940 case lltok::kw_srem:
5941 return parseArithmetic(Inst, PFS, KeywordVal,
5942 /*IsFP*/ false);
5943 case lltok::kw_and:
5944 case lltok::kw_or:
5945 case lltok::kw_xor:
5946 return parseLogical(Inst, PFS, KeywordVal);
5947 case lltok::kw_icmp:
5948 return parseCompare(Inst, PFS, KeywordVal);
5949 case lltok::kw_fcmp: {
5950 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5951 int Res = parseCompare(Inst, PFS, KeywordVal);
5952 if (Res != 0)
5953 return Res;
5954 if (FMF.any())
5955 Inst->setFastMathFlags(FMF);
5956 return 0;
5957 }
5958
5959 // Casts.
5960 case lltok::kw_trunc:
5961 case lltok::kw_zext:
5962 case lltok::kw_sext:
5963 case lltok::kw_fptrunc:
5964 case lltok::kw_fpext:
5965 case lltok::kw_bitcast:
5966 case lltok::kw_addrspacecast:
5967 case lltok::kw_uitofp:
5968 case lltok::kw_sitofp:
5969 case lltok::kw_fptoui:
5970 case lltok::kw_fptosi:
5971 case lltok::kw_inttoptr:
5972 case lltok::kw_ptrtoint:
5973 return parseCast(Inst, PFS, KeywordVal);
5974 // Other.
5975 case lltok::kw_select: {
5976 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5977 int Res = parseSelect(Inst, PFS);
5978 if (Res != 0)
5979 return Res;
5980 if (FMF.any()) {
5981 if (!isa<FPMathOperator>(Inst))
5982 return error(Loc, "fast-math-flags specified for select without "
5983 "floating-point scalar or vector return type");
5984 Inst->setFastMathFlags(FMF);
5985 }
5986 return 0;
5987 }
5988 case lltok::kw_va_arg:
5989 return parseVAArg(Inst, PFS);
5990 case lltok::kw_extractelement:
5991 return parseExtractElement(Inst, PFS);
5992 case lltok::kw_insertelement:
5993 return parseInsertElement(Inst, PFS);
5994 case lltok::kw_shufflevector:
5995 return parseShuffleVector(Inst, PFS);
5996 case lltok::kw_phi: {
5997 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5998 int Res = parsePHI(Inst, PFS);
5999 if (Res != 0)
6000 return Res;
6001 if (FMF.any()) {
6002 if (!isa<FPMathOperator>(Inst))
6003 return error(Loc, "fast-math-flags specified for phi without "
6004 "floating-point scalar or vector return type");
6005 Inst->setFastMathFlags(FMF);
6006 }
6007 return 0;
6008 }
6009 case lltok::kw_landingpad:
6010 return parseLandingPad(Inst, PFS);
6011 case lltok::kw_freeze:
6012 return parseFreeze(Inst, PFS);
6013 // Call.
6014 case lltok::kw_call:
6015 return parseCall(Inst, PFS, CallInst::TCK_None);
6016 case lltok::kw_tail:
6017 return parseCall(Inst, PFS, CallInst::TCK_Tail);
6018 case lltok::kw_musttail:
6019 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
6020 case lltok::kw_notail:
6021 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
6022 // Memory.
6023 case lltok::kw_alloca:
6024 return parseAlloc(Inst, PFS);
6025 case lltok::kw_load:
6026 return parseLoad(Inst, PFS);
6027 case lltok::kw_store:
6028 return parseStore(Inst, PFS);
6029 case lltok::kw_cmpxchg:
6030 return parseCmpXchg(Inst, PFS);
6031 case lltok::kw_atomicrmw:
6032 return parseAtomicRMW(Inst, PFS);
6033 case lltok::kw_fence:
6034 return parseFence(Inst, PFS);
6035 case lltok::kw_getelementptr:
6036 return parseGetElementPtr(Inst, PFS);
6037 case lltok::kw_extractvalue:
6038 return parseExtractValue(Inst, PFS);
6039 case lltok::kw_insertvalue:
6040 return parseInsertValue(Inst, PFS);
6041 }
6042}
6043
6044/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
6045bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
6046 if (Opc == Instruction::FCmp) {
6047 switch (Lex.getKind()) {
6048 default:
6049 return tokError("expected fcmp predicate (e.g. 'oeq')");
6050 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
6051 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
6052 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
6053 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
6054 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
6055 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
6056 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
6057 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
6058 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
6059 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
6060 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
6061 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
6062 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
6063 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
6064 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
6065 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
6066 }
6067 } else {
6068 switch (Lex.getKind()) {
6069 default:
6070 return tokError("expected icmp predicate (e.g. 'eq')");
6071 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
6072 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
6073 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
6074 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
6075 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
6076 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
6077 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
6078 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
6079 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
6080 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
6081 }
6082 }
6083 Lex.Lex();
6084 return false;
6085}
6086
6087//===----------------------------------------------------------------------===//
6088// Terminator Instructions.
6089//===----------------------------------------------------------------------===//
6090
6091/// parseRet - parse a return instruction.
6092/// ::= 'ret' void (',' !dbg, !1)*
6093/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
6094bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
6095 PerFunctionState &PFS) {
6096 SMLoc TypeLoc = Lex.getLoc();
6097 Type *Ty = nullptr;
6098 if (parseType(Ty, true /*void allowed*/))
6099 return true;
6100
6101 Type *ResType = PFS.getFunction().getReturnType();
6102
6103 if (Ty->isVoidTy()) {
6104 if (!ResType->isVoidTy())
6105 return error(TypeLoc, "value doesn't match function result type '" +
6106 getTypeString(ResType) + "'");
6107
6108 Inst = ReturnInst::Create(Context);
6109 return false;
6110 }
6111
6112 Value *RV;
6113 if (parseValue(Ty, RV, PFS))
6114 return true;
6115
6116 if (ResType != RV->getType())
6117 return error(TypeLoc, "value doesn't match function result type '" +
6118 getTypeString(ResType) + "'");
6119
6120 Inst = ReturnInst::Create(Context, RV);
6121 return false;
6122}
6123
6124/// parseBr
6125/// ::= 'br' TypeAndValue
6126/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6127bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
6128 LocTy Loc, Loc2;
6129 Value *Op0;
6130 BasicBlock *Op1, *Op2;
6131 if (parseTypeAndValue(Op0, Loc, PFS))
6132 return true;
6133
6134 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
6135 Inst = BranchInst::Create(BB);
6136 return false;
6137 }
6138
6139 if (Op0->getType() != Type::getInt1Ty(Context))
6140 return error(Loc, "branch condition must have 'i1' type");
6141
6142 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
6143 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
6144 parseToken(lltok::comma, "expected ',' after true destination") ||
6145 parseTypeAndBasicBlock(Op2, Loc2, PFS))
6146 return true;
6147
6148 Inst = BranchInst::Create(Op1, Op2, Op0);
6149 return false;
6150}
6151
6152/// parseSwitch
6153/// Instruction
6154/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
6155/// JumpTable
6156/// ::= (TypeAndValue ',' TypeAndValue)*
6157bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6158 LocTy CondLoc, BBLoc;
6159 Value *Cond;
6160 BasicBlock *DefaultBB;
6161 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
6162 parseToken(lltok::comma, "expected ',' after switch condition") ||
6163 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
6164 parseToken(lltok::lsquare, "expected '[' with switch table"))
6165 return true;
6166
6167 if (!Cond->getType()->isIntegerTy())
6168 return error(CondLoc, "switch condition must have integer type");
6169
6170 // parse the jump table pairs.
6171 SmallPtrSet<Value*, 32> SeenCases;
6172 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
6173 while (Lex.getKind() != lltok::rsquare) {
6174 Value *Constant;
6175 BasicBlock *DestBB;
6176
6177 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
6178 parseToken(lltok::comma, "expected ',' after case value") ||
6179 parseTypeAndBasicBlock(DestBB, PFS))
6180 return true;
6181
6182 if (!SeenCases.insert(Constant).second)
6183 return error(CondLoc, "duplicate case value in switch");
6184 if (!isa<ConstantInt>(Constant))
6185 return error(CondLoc, "case value is not a constant integer");
6186
6187 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
6188 }
6189
6190 Lex.Lex(); // Eat the ']'.
6191
6192 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
6193 for (unsigned i = 0, e = Table.size(); i != e; ++i)
6194 SI->addCase(Table[i].first, Table[i].second);
6195 Inst = SI;
6196 return false;
6197}
6198
6199/// parseIndirectBr
6200/// Instruction
6201/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
6202bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
6203 LocTy AddrLoc;
6204 Value *Address;
6205 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
6206 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
6207 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
6208 return true;
6209
6210 if (!Address->getType()->isPointerTy())
6211 return error(AddrLoc, "indirectbr address must have pointer type");
6212
6213 // parse the destination list.
6214 SmallVector<BasicBlock*, 16> DestList;
6215
6216 if (Lex.getKind() != lltok::rsquare) {
6217 BasicBlock *DestBB;
6218 if (parseTypeAndBasicBlock(DestBB, PFS))
6219 return true;
6220 DestList.push_back(DestBB);
6221
6222 while (EatIfPresent(lltok::comma)) {
6223 if (parseTypeAndBasicBlock(DestBB, PFS))
6224 return true;
6225 DestList.push_back(DestBB);
6226 }
6227 }
6228
6229 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6230 return true;
6231
6232 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
6233 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
6234 IBI->addDestination(DestList[i]);
6235 Inst = IBI;
6236 return false;
6237}
6238
6239/// parseInvoke
6240/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6241/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6242bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6243 LocTy CallLoc = Lex.getLoc();
6244 AttrBuilder RetAttrs, FnAttrs;
6245 std::vector<unsigned> FwdRefAttrGrps;
6246 LocTy NoBuiltinLoc;
6247 unsigned CC;
6248 unsigned InvokeAddrSpace;
6249 Type *RetType = nullptr;
6250 LocTy RetTypeLoc;
6251 ValID CalleeID;
6252 SmallVector<ParamInfo, 16> ArgList;
6253 SmallVector<OperandBundleDef, 2> BundleList;
6254
6255 BasicBlock *NormalBB, *UnwindBB;
6256 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6257 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
6258 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6259 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
6260 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6261 NoBuiltinLoc) ||
6262 parseOptionalOperandBundles(BundleList, PFS) ||
6263 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
6264 parseTypeAndBasicBlock(NormalBB, PFS) ||
6265 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
6266 parseTypeAndBasicBlock(UnwindBB, PFS))
6267 return true;
6268
6269 // If RetType is a non-function pointer type, then this is the short syntax
6270 // for the call, which means that RetType is just the return type. Infer the
6271 // rest of the function argument types from the arguments that are present.
6272 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6273 if (!Ty) {
6274 // Pull out the types of all of the arguments...
6275 std::vector<Type*> ParamTypes;
6276 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6277 ParamTypes.push_back(ArgList[i].V->getType());
6278
6279 if (!FunctionType::isValidReturnType(RetType))
6280 return error(RetTypeLoc, "Invalid result type for LLVM function");
6281
6282 Ty = FunctionType::get(RetType, ParamTypes, false);
6283 }
6284
6285 CalleeID.FTy = Ty;
6286
6287 // Look up the callee.
6288 Value *Callee;
6289 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6290 Callee, &PFS, /*IsCall=*/true))
6291 return true;
6292
6293 // Set up the Attribute for the function.
6294 SmallVector<Value *, 8> Args;
6295 SmallVector<AttributeSet, 8> ArgAttrs;
6296
6297 // Loop through FunctionType's arguments and ensure they are specified
6298 // correctly. Also, gather any parameter attributes.
6299 FunctionType::param_iterator I = Ty->param_begin();
6300 FunctionType::param_iterator E = Ty->param_end();
6301 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6302 Type *ExpectedTy = nullptr;
6303 if (I != E) {
6304 ExpectedTy = *I++;
6305 } else if (!Ty->isVarArg()) {
6306 return error(ArgList[i].Loc, "too many arguments specified");
6307 }
6308
6309 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6310 return error(ArgList[i].Loc, "argument is not of expected type '" +
6311 getTypeString(ExpectedTy) + "'");
6312 Args.push_back(ArgList[i].V);
6313 ArgAttrs.push_back(ArgList[i].Attrs);
6314 }
6315
6316 if (I != E)
6317 return error(CallLoc, "not enough parameters specified for call");
6318
6319 if (FnAttrs.hasAlignmentAttr())
6320 return error(CallLoc, "invoke instructions may not have an alignment");
6321
6322 // Finish off the Attribute and check them
6323 AttributeList PAL =
6324 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6325 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6326
6327 InvokeInst *II =
6328 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
6329 II->setCallingConv(CC);
6330 II->setAttributes(PAL);
6331 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
6332 Inst = II;
6333 return false;
6334}
6335
6336/// parseResume
6337/// ::= 'resume' TypeAndValue
6338bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
6339 Value *Exn; LocTy ExnLoc;
6340 if (parseTypeAndValue(Exn, ExnLoc, PFS))
6341 return true;
6342
6343 ResumeInst *RI = ResumeInst::Create(Exn);
6344 Inst = RI;
6345 return false;
6346}
6347
6348bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
6349 PerFunctionState &PFS) {
6350 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
6351 return true;
6352
6353 while (Lex.getKind() != lltok::rsquare) {
6354 // If this isn't the first argument, we need a comma.
6355 if (!Args.empty() &&
6356 parseToken(lltok::comma, "expected ',' in argument list"))
6357 return true;
6358
6359 // parse the argument.
6360 LocTy ArgLoc;
6361 Type *ArgTy = nullptr;
6362 if (parseType(ArgTy, ArgLoc))
6363 return true;
6364
6365 Value *V;
6366 if (ArgTy->isMetadataTy()) {
6367 if (parseMetadataAsValue(V, PFS))
6368 return true;
6369 } else {
6370 if (parseValue(ArgTy, V, PFS))
6371 return true;
6372 }
6373 Args.push_back(V);
6374 }
6375
6376 Lex.Lex(); // Lex the ']'.
6377 return false;
6378}
6379
6380/// parseCleanupRet
6381/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6382bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6383 Value *CleanupPad = nullptr;
6384
6385 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6386 return true;
6387
6388 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6389 return true;
6390
6391 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6392 return true;
6393
6394 BasicBlock *UnwindBB = nullptr;
6395 if (Lex.getKind() == lltok::kw_to) {
6396 Lex.Lex();
6397 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6398 return true;
6399 } else {
6400 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
6401 return true;
6402 }
6403 }
6404
6405 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6406 return false;
6407}
6408
6409/// parseCatchRet
6410/// ::= 'catchret' from Parent Value 'to' TypeAndValue
6411bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6412 Value *CatchPad = nullptr;
6413
6414 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
6415 return true;
6416
6417 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
6418 return true;
6419
6420 BasicBlock *BB;
6421 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
6422 parseTypeAndBasicBlock(BB, PFS))
6423 return true;
6424
6425 Inst = CatchReturnInst::Create(CatchPad, BB);
6426 return false;
6427}
6428
6429/// parseCatchSwitch
6430/// ::= 'catchswitch' within Parent
6431bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6432 Value *ParentPad;
6433
6434 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6435 return true;
6436
6437 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6438 Lex.getKind() != lltok::LocalVarID)
6439 return tokError("expected scope value for catchswitch");
6440
6441 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6442 return true;
6443
6444 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6445 return true;
6446
6447 SmallVector<BasicBlock *, 32> Table;
6448 do {
6449 BasicBlock *DestBB;
6450 if (parseTypeAndBasicBlock(DestBB, PFS))
6451 return true;
6452 Table.push_back(DestBB);
6453 } while (EatIfPresent(lltok::comma));
6454
6455 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6456 return true;
6457
6458 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
6459 return true;
6460
6461 BasicBlock *UnwindBB = nullptr;
6462 if (EatIfPresent(lltok::kw_to)) {
6463 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6464 return true;
6465 } else {
6466 if (parseTypeAndBasicBlock(UnwindBB, PFS))
6467 return true;
6468 }
6469
6470 auto *CatchSwitch =
6471 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6472 for (BasicBlock *DestBB : Table)
6473 CatchSwitch->addHandler(DestBB);
6474 Inst = CatchSwitch;
6475 return false;
6476}
6477
6478/// parseCatchPad
6479/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6480bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6481 Value *CatchSwitch = nullptr;
6482
6483 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
6484 return true;
6485
6486 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6487 return tokError("expected scope value for catchpad");
6488
6489 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6490 return true;
6491
6492 SmallVector<Value *, 8> Args;
6493 if (parseExceptionArgs(Args, PFS))
6494 return true;
6495
6496 Inst = CatchPadInst::Create(CatchSwitch, Args);
6497 return false;
6498}
6499
6500/// parseCleanupPad
6501/// ::= 'cleanuppad' within Parent ParamList
6502bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6503 Value *ParentPad = nullptr;
6504
6505 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6506 return true;
6507
6508 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6509 Lex.getKind() != lltok::LocalVarID)
6510 return tokError("expected scope value for cleanuppad");
6511
6512 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6513 return true;
6514
6515 SmallVector<Value *, 8> Args;
6516 if (parseExceptionArgs(Args, PFS))
6517 return true;
6518
6519 Inst = CleanupPadInst::Create(ParentPad, Args);
6520 return false;
6521}
6522
6523//===----------------------------------------------------------------------===//
6524// Unary Operators.
6525//===----------------------------------------------------------------------===//
6526
6527/// parseUnaryOp
6528/// ::= UnaryOp TypeAndValue ',' Value
6529///
6530/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6531/// operand is allowed.
6532bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6533 unsigned Opc, bool IsFP) {
6534 LocTy Loc; Value *LHS;
6535 if (parseTypeAndValue(LHS, Loc, PFS))
6536 return true;
6537
6538 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6539 : LHS->getType()->isIntOrIntVectorTy();
6540
6541 if (!Valid)
6542 return error(Loc, "invalid operand type for instruction");
6543
6544 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6545 return false;
6546}
6547
6548/// parseCallBr
6549/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6550/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6551/// '[' LabelList ']'
6552bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6553 LocTy CallLoc = Lex.getLoc();
6554 AttrBuilder RetAttrs, FnAttrs;
6555 std::vector<unsigned> FwdRefAttrGrps;
6556 LocTy NoBuiltinLoc;
6557 unsigned CC;
6558 Type *RetType = nullptr;
6559 LocTy RetTypeLoc;
6560 ValID CalleeID;
6561 SmallVector<ParamInfo, 16> ArgList;
6562 SmallVector<OperandBundleDef, 2> BundleList;
6563
6564 BasicBlock *DefaultDest;
6565 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6566 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6567 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
6568 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6569 NoBuiltinLoc) ||
6570 parseOptionalOperandBundles(BundleList, PFS) ||
6571 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
6572 parseTypeAndBasicBlock(DefaultDest, PFS) ||
6573 parseToken(lltok::lsquare, "expected '[' in callbr"))
6574 return true;
6575
6576 // parse the destination list.
6577 SmallVector<BasicBlock *, 16> IndirectDests;
6578
6579 if (Lex.getKind() != lltok::rsquare) {
6580 BasicBlock *DestBB;
6581 if (parseTypeAndBasicBlock(DestBB, PFS))
6582 return true;
6583 IndirectDests.push_back(DestBB);
6584
6585 while (EatIfPresent(lltok::comma)) {
6586 if (parseTypeAndBasicBlock(DestBB, PFS))
6587 return true;
6588 IndirectDests.push_back(DestBB);
6589 }
6590 }
6591
6592 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6593 return true;
6594
6595 // If RetType is a non-function pointer type, then this is the short syntax
6596 // for the call, which means that RetType is just the return type. Infer the
6597 // rest of the function argument types from the arguments that are present.
6598 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6599 if (!Ty) {
6600 // Pull out the types of all of the arguments...
6601 std::vector<Type *> ParamTypes;
6602 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6603 ParamTypes.push_back(ArgList[i].V->getType());
6604
6605 if (!FunctionType::isValidReturnType(RetType))
6606 return error(RetTypeLoc, "Invalid result type for LLVM function");
6607
6608 Ty = FunctionType::get(RetType, ParamTypes, false);
6609 }
6610
6611 CalleeID.FTy = Ty;
6612
6613 // Look up the callee.
6614 Value *Callee;
6615 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
6616 /*IsCall=*/true))
6617 return true;
6618
6619 // Set up the Attribute for the function.
6620 SmallVector<Value *, 8> Args;
6621 SmallVector<AttributeSet, 8> ArgAttrs;
6622
6623 // Loop through FunctionType's arguments and ensure they are specified
6624 // correctly. Also, gather any parameter attributes.
6625 FunctionType::param_iterator I = Ty->param_begin();
6626 FunctionType::param_iterator E = Ty->param_end();
6627 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6628 Type *ExpectedTy = nullptr;
6629 if (I != E) {
6630 ExpectedTy = *I++;
6631 } else if (!Ty->isVarArg()) {
6632 return error(ArgList[i].Loc, "too many arguments specified");
6633 }
6634
6635 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6636 return error(ArgList[i].Loc, "argument is not of expected type '" +
6637 getTypeString(ExpectedTy) + "'");
6638 Args.push_back(ArgList[i].V);
6639 ArgAttrs.push_back(ArgList[i].Attrs);
6640 }
6641
6642 if (I != E)
6643 return error(CallLoc, "not enough parameters specified for call");
6644
6645 if (FnAttrs.hasAlignmentAttr())
6646 return error(CallLoc, "callbr instructions may not have an alignment");
6647
6648 // Finish off the Attribute and check them
6649 AttributeList PAL =
6650 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6651 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6652
6653 CallBrInst *CBI =
6654 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
6655 BundleList);
6656 CBI->setCallingConv(CC);
6657 CBI->setAttributes(PAL);
6658 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
6659 Inst = CBI;
6660 return false;
6661}
6662
6663//===----------------------------------------------------------------------===//
6664// Binary Operators.
6665//===----------------------------------------------------------------------===//
6666
6667/// parseArithmetic
6668/// ::= ArithmeticOps TypeAndValue ',' Value
6669///
6670/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6671/// operand is allowed.
6672bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
6673 unsigned Opc, bool IsFP) {
6674 LocTy Loc; Value *LHS, *RHS;
6675 if (parseTypeAndValue(LHS, Loc, PFS) ||
6676 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6677 parseValue(LHS->getType(), RHS, PFS))
6678 return true;
6679
6680 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6681 : LHS->getType()->isIntOrIntVectorTy();
6682
6683 if (!Valid)
6684 return error(Loc, "invalid operand type for instruction");
6685
6686 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6687 return false;
6688}
6689
6690/// parseLogical
6691/// ::= ArithmeticOps TypeAndValue ',' Value {
6692bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
6693 unsigned Opc) {
6694 LocTy Loc; Value *LHS, *RHS;
6695 if (parseTypeAndValue(LHS, Loc, PFS) ||
6696 parseToken(lltok::comma, "expected ',' in logical operation") ||
6697 parseValue(LHS->getType(), RHS, PFS))
6698 return true;
6699
6700 if (!LHS->getType()->isIntOrIntVectorTy())
6701 return error(Loc,
6702 "instruction requires integer or integer vector operands");
6703
6704 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6705 return false;
6706}
6707
6708/// parseCompare
6709/// ::= 'icmp' IPredicates TypeAndValue ',' Value
6710/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
6711bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
6712 unsigned Opc) {
6713 // parse the integer/fp comparison predicate.
6714 LocTy Loc;
6715 unsigned Pred;
6716 Value *LHS, *RHS;
6717 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
6718 parseToken(lltok::comma, "expected ',' after compare value") ||
6719 parseValue(LHS->getType(), RHS, PFS))
6720 return true;
6721
6722 if (Opc == Instruction::FCmp) {
6723 if (!LHS->getType()->isFPOrFPVectorTy())
6724 return error(Loc, "fcmp requires floating point operands");
6725 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6726 } else {
6727 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!")((void)0);
6728 if (!LHS->getType()->isIntOrIntVectorTy() &&
6729 !LHS->getType()->isPtrOrPtrVectorTy())
6730 return error(Loc, "icmp requires integer operands");
6731 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6732 }
6733 return false;
6734}
6735
6736//===----------------------------------------------------------------------===//
6737// Other Instructions.
6738//===----------------------------------------------------------------------===//
6739
6740/// parseCast
6741/// ::= CastOpc TypeAndValue 'to' Type
6742bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
6743 unsigned Opc) {
6744 LocTy Loc;
6745 Value *Op;
6746 Type *DestTy = nullptr;
6747 if (parseTypeAndValue(Op, Loc, PFS) ||
6748 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
6749 parseType(DestTy))
6750 return true;
6751
6752 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6753 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
6754 return error(Loc, "invalid cast opcode for cast from '" +
6755 getTypeString(Op->getType()) + "' to '" +
6756 getTypeString(DestTy) + "'");
6757 }
6758 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6759 return false;
6760}
6761
6762/// parseSelect
6763/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6764bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6765 LocTy Loc;
6766 Value *Op0, *Op1, *Op2;
6767 if (parseTypeAndValue(Op0, Loc, PFS) ||
6768 parseToken(lltok::comma, "expected ',' after select condition") ||
6769 parseTypeAndValue(Op1, PFS) ||
6770 parseToken(lltok::comma, "expected ',' after select value") ||
6771 parseTypeAndValue(Op2, PFS))
6772 return true;
6773
6774 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6775 return error(Loc, Reason);
6776
6777 Inst = SelectInst::Create(Op0, Op1, Op2);
6778 return false;
6779}
6780
6781/// parseVAArg
6782/// ::= 'va_arg' TypeAndValue ',' Type
6783bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
6784 Value *Op;
6785 Type *EltTy = nullptr;
6786 LocTy TypeLoc;
6787 if (parseTypeAndValue(Op, PFS) ||
6788 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
6789 parseType(EltTy, TypeLoc))
6790 return true;
6791
6792 if (!EltTy->isFirstClassType())
6793 return error(TypeLoc, "va_arg requires operand with first class type");
6794
6795 Inst = new VAArgInst(Op, EltTy);
6796 return false;
6797}
6798
6799/// parseExtractElement
6800/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6801bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6802 LocTy Loc;
6803 Value *Op0, *Op1;
6804 if (parseTypeAndValue(Op0, Loc, PFS) ||
6805 parseToken(lltok::comma, "expected ',' after extract value") ||
6806 parseTypeAndValue(Op1, PFS))
6807 return true;
6808
6809 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6810 return error(Loc, "invalid extractelement operands");
6811
6812 Inst = ExtractElementInst::Create(Op0, Op1);
6813 return false;
6814}
6815
6816/// parseInsertElement
6817/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6818bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6819 LocTy Loc;
6820 Value *Op0, *Op1, *Op2;
6821 if (parseTypeAndValue(Op0, Loc, PFS) ||
6822 parseToken(lltok::comma, "expected ',' after insertelement value") ||
6823 parseTypeAndValue(Op1, PFS) ||
6824 parseToken(lltok::comma, "expected ',' after insertelement value") ||
6825 parseTypeAndValue(Op2, PFS))
6826 return true;
6827
6828 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
6829 return error(Loc, "invalid insertelement operands");
6830
6831 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6832 return false;
6833}
6834
6835/// parseShuffleVector
6836/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6837bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6838 LocTy Loc;
6839 Value *Op0, *Op1, *Op2;
6840 if (parseTypeAndValue(Op0, Loc, PFS) ||
6841 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
6842 parseTypeAndValue(Op1, PFS) ||
6843 parseToken(lltok::comma, "expected ',' after shuffle value") ||
6844 parseTypeAndValue(Op2, PFS))
6845 return true;
6846
6847 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
6848 return error(Loc, "invalid shufflevector operands");
6849
6850 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6851 return false;
6852}
6853
6854/// parsePHI
6855/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6856int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
6857 Type *Ty = nullptr; LocTy TypeLoc;
6858 Value *Op0, *Op1;
6859
6860 if (parseType(Ty, TypeLoc) ||
6861 parseToken(lltok::lsquare, "expected '[' in phi value list") ||
6862 parseValue(Ty, Op0, PFS) ||
6863 parseToken(lltok::comma, "expected ',' after insertelement value") ||
6864 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
6865 parseToken(lltok::rsquare, "expected ']' in phi value list"))
6866 return true;
6867
6868 bool AteExtraComma = false;
6869 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
6870
6871 while (true) {
6872 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
6873
6874 if (!EatIfPresent(lltok::comma))
6875 break;
6876
6877 if (Lex.getKind() == lltok::MetadataVar) {
6878 AteExtraComma = true;
6879 break;
6880 }
6881
6882 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
6883 parseValue(Ty, Op0, PFS) ||
6884 parseToken(lltok::comma, "expected ',' after insertelement value") ||
6885 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
6886 parseToken(lltok::rsquare, "expected ']' in phi value list"))
6887 return true;
6888 }
6889
6890 if (!Ty->isFirstClassType())
6891 return error(TypeLoc, "phi node must have first class type");
6892
6893 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
6894 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6895 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6896 Inst = PN;
6897 return AteExtraComma ? InstExtraComma : InstNormal;
6898}
6899
6900/// parseLandingPad
6901/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6902/// Clause
6903/// ::= 'catch' TypeAndValue
6904/// ::= 'filter'
6905/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6906bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
6907 Type *Ty = nullptr; LocTy TyLoc;
6908
6909 if (parseType(Ty, TyLoc))
6910 return true;
6911
6912 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
6913 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6914
6915 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6916 LandingPadInst::ClauseType CT;
6917 if (EatIfPresent(lltok::kw_catch))
6918 CT = LandingPadInst::Catch;
6919 else if (EatIfPresent(lltok::kw_filter))
6920 CT = LandingPadInst::Filter;
6921 else
6922 return tokError("expected 'catch' or 'filter' clause type");
6923
6924 Value *V;
6925 LocTy VLoc;
6926 if (parseTypeAndValue(V, VLoc, PFS))
6927 return true;
6928
6929 // A 'catch' type expects a non-array constant. A filter clause expects an
6930 // array constant.
6931 if (CT == LandingPadInst::Catch) {
6932 if (isa<ArrayType>(V->getType()))
6933 error(VLoc, "'catch' clause has an invalid type");
6934 } else {
6935 if (!isa<ArrayType>(V->getType()))
6936 error(VLoc, "'filter' clause has an invalid type");
6937 }
6938
6939 Constant *CV = dyn_cast<Constant>(V);
6940 if (!CV)
6941 return error(VLoc, "clause argument must be a constant");
6942 LP->addClause(CV);
6943 }
6944
6945 Inst = LP.release();
6946 return false;
6947}
6948
6949/// parseFreeze
6950/// ::= 'freeze' Type Value
6951bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
6952 LocTy Loc;
6953 Value *Op;
6954 if (parseTypeAndValue(Op, Loc, PFS))
6955 return true;
6956
6957 Inst = new FreezeInst(Op);
6958 return false;
6959}
6960
6961/// parseCall
6962/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6963/// OptionalAttrs Type Value ParameterList OptionalAttrs
6964/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6965/// OptionalAttrs Type Value ParameterList OptionalAttrs
6966/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6967/// OptionalAttrs Type Value ParameterList OptionalAttrs
6968/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6969/// OptionalAttrs Type Value ParameterList OptionalAttrs
6970bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
6971 CallInst::TailCallKind TCK) {
6972 AttrBuilder RetAttrs, FnAttrs;
6973 std::vector<unsigned> FwdRefAttrGrps;
6974 LocTy BuiltinLoc;
6975 unsigned CallAddrSpace;
6976 unsigned CC;
6977 Type *RetType = nullptr;
6978 LocTy RetTypeLoc;
6979 ValID CalleeID;
6980 SmallVector<ParamInfo, 16> ArgList;
6981 SmallVector<OperandBundleDef, 2> BundleList;
6982 LocTy CallLoc = Lex.getLoc();
6983
6984 if (TCK != CallInst::TCK_None &&
6985 parseToken(lltok::kw_call,
6986 "expected 'tail call', 'musttail call', or 'notail call'"))
6987 return true;
6988
6989 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6990
6991 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6992 parseOptionalProgramAddrSpace(CallAddrSpace) ||
6993 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6994 parseValID(CalleeID, &PFS) ||
6995 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6996 PFS.getFunction().isVarArg()) ||
6997 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6998 parseOptionalOperandBundles(BundleList, PFS))
6999 return true;
7000
7001 // If RetType is a non-function pointer type, then this is the short syntax
7002 // for the call, which means that RetType is just the return type. Infer the
7003 // rest of the function argument types from the arguments that are present.
7004 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
7005 if (!Ty) {
7006 // Pull out the types of all of the arguments...
7007 std::vector<Type*> ParamTypes;
7008 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
7009 ParamTypes.push_back(ArgList[i].V->getType());
7010
7011 if (!FunctionType::isValidReturnType(RetType))
7012 return error(RetTypeLoc, "Invalid result type for LLVM function");
7013
7014 Ty = FunctionType::get(RetType, ParamTypes, false);
7015 }
7016
7017 CalleeID.FTy = Ty;
7018
7019 // Look up the callee.
7020 Value *Callee;
7021 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7022 &PFS, /*IsCall=*/true))
7023 return true;
7024
7025 // Set up the Attribute for the function.
7026 SmallVector<AttributeSet, 8> Attrs;
7027
7028 SmallVector<Value*, 8> Args;
7029
7030 // Loop through FunctionType's arguments and ensure they are specified
7031 // correctly. Also, gather any parameter attributes.
7032 FunctionType::param_iterator I = Ty->param_begin();
7033 FunctionType::param_iterator E = Ty->param_end();
7034 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7035 Type *ExpectedTy = nullptr;
7036 if (I != E) {
7037 ExpectedTy = *I++;
7038 } else if (!Ty->isVarArg()) {
7039 return error(ArgList[i].Loc, "too many arguments specified");
7040 }
7041
7042 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7043 return error(ArgList[i].Loc, "argument is not of expected type '" +
7044 getTypeString(ExpectedTy) + "'");
7045 Args.push_back(ArgList[i].V);
7046 Attrs.push_back(ArgList[i].Attrs);
7047 }
7048
7049 if (I != E)
7050 return error(CallLoc, "not enough parameters specified for call");
7051
7052 if (FnAttrs.hasAlignmentAttr())
7053 return error(CallLoc, "call instructions may not have an alignment");
7054
7055 // Finish off the Attribute and check them
7056 AttributeList PAL =
7057 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7058 AttributeSet::get(Context, RetAttrs), Attrs);
7059
7060 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
7061 CI->setTailCallKind(TCK);
7062 CI->setCallingConv(CC);
7063 if (FMF.any()) {
7064 if (!isa<FPMathOperator>(CI)) {
7065 CI->deleteValue();
7066 return error(CallLoc, "fast-math-flags specified for call without "
7067 "floating-point scalar or vector return type");
7068 }
7069 CI->setFastMathFlags(FMF);
7070 }
7071 CI->setAttributes(PAL);
7072 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7073 Inst = CI;
7074 return false;
7075}
7076
7077//===----------------------------------------------------------------------===//
7078// Memory Instructions.
7079//===----------------------------------------------------------------------===//
7080
7081/// parseAlloc
7082/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7083/// (',' 'align' i32)? (',', 'addrspace(n))?
7084int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
7085 Value *Size = nullptr;
7086 LocTy SizeLoc, TyLoc, ASLoc;
7087 MaybeAlign Alignment;
7088 unsigned AddrSpace = 0;
7089 Type *Ty = nullptr;
7090
7091 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7092 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
7093
7094 if (parseType(Ty, TyLoc))
7095 return true;
7096
7097 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
7098 return error(TyLoc, "invalid type for alloca");
7099
7100 bool AteExtraComma = false;
7101 if (EatIfPresent(lltok::comma)) {
7102 if (Lex.getKind() == lltok::kw_align) {
7103 if (parseOptionalAlignment(Alignment))
7104 return true;
7105 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7106 return true;
7107 } else if (Lex.getKind() == lltok::kw_addrspace) {
7108 ASLoc = Lex.getLoc();
7109 if (parseOptionalAddrSpace(AddrSpace))
7110 return true;
7111 } else if (Lex.getKind() == lltok::MetadataVar) {
7112 AteExtraComma = true;
7113 } else {
7114 if (parseTypeAndValue(Size, SizeLoc, PFS))
7115 return true;
7116 if (EatIfPresent(lltok::comma)) {
7117 if (Lex.getKind() == lltok::kw_align) {
7118 if (parseOptionalAlignment(Alignment))
7119 return true;
7120 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7121 return true;
7122 } else if (Lex.getKind() == lltok::kw_addrspace) {
7123 ASLoc = Lex.getLoc();
7124 if (parseOptionalAddrSpace(AddrSpace))
7125 return true;
7126 } else if (Lex.getKind() == lltok::MetadataVar) {
7127 AteExtraComma = true;
7128 }
7129 }
7130 }
7131 }
7132
7133 if (Size && !Size->getType()->isIntegerTy())
7134 return error(SizeLoc, "element count must have integer type");
7135
7136 SmallPtrSet<Type *, 4> Visited;
7137 if (!Alignment && !Ty->isSized(&Visited))
7138 return error(TyLoc, "Cannot allocate unsized type");
7139 if (!Alignment)
7140 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
7141 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
7142 AI->setUsedWithInAlloca(IsInAlloca);
7143 AI->setSwiftError(IsSwiftError);
7144 Inst = AI;
7145 return AteExtraComma ? InstExtraComma : InstNormal;
7146}
7147
7148/// parseLoad
7149/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
7150/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
7151/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7152int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
7153 Value *Val; LocTy Loc;
7154 MaybeAlign Alignment;
7155 bool AteExtraComma = false;
7156 bool isAtomic = false;
7157 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7158 SyncScope::ID SSID = SyncScope::System;
7159
7160 if (Lex.getKind() == lltok::kw_atomic) {
7161 isAtomic = true;
7162 Lex.Lex();
7163 }
7164
7165 bool isVolatile = false;
7166 if (Lex.getKind() == lltok::kw_volatile) {
7167 isVolatile = true;
7168 Lex.Lex();
7169 }
7170
7171 Type *Ty;
7172 LocTy ExplicitTypeLoc = Lex.getLoc();
7173 if (parseType(Ty) ||
7174 parseToken(lltok::comma, "expected comma after load's type") ||
7175 parseTypeAndValue(Val, Loc, PFS) ||
7176 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7177 parseOptionalCommaAlign(Alignment, AteExtraComma))
7178 return true;
7179
7180 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
7181 return error(Loc, "load operand must be a pointer to a first class type");
7182 if (isAtomic && !Alignment)
7183 return error(Loc, "atomic load must have explicit non-zero alignment");
7184 if (Ordering == AtomicOrdering::Release ||
7185 Ordering == AtomicOrdering::AcquireRelease)
7186 return error(Loc, "atomic load cannot use Release ordering");
7187
7188 if (!cast<PointerType>(Val->getType())->isOpaqueOrPointeeTypeMatches(Ty)) {
7189 return error(
7190 ExplicitTypeLoc,
7191 typeComparisonErrorMessage(
7192 "explicit pointee type doesn't match operand's pointee type", Ty,
7193 cast<PointerType>(Val->getType())->getElementType()));
7194 }
7195 SmallPtrSet<Type *, 4> Visited;
7196 if (!Alignment && !Ty->isSized(&Visited))
7197 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
7198 if (!Alignment)
7199 Alignment = M->getDataLayout().getABITypeAlign(Ty);
7200 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
7201 return AteExtraComma ? InstExtraComma : InstNormal;
7202}
7203
7204/// parseStore
7205
7206/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
7207/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
7208/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7209int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
7210 Value *Val, *Ptr; LocTy Loc, PtrLoc;
7211 MaybeAlign Alignment;
7212 bool AteExtraComma = false;
7213 bool isAtomic = false;
7214 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7215 SyncScope::ID SSID = SyncScope::System;
7216
7217 if (Lex.getKind() == lltok::kw_atomic) {
7218 isAtomic = true;
7219 Lex.Lex();
7220 }
7221
7222 bool isVolatile = false;
7223 if (Lex.getKind() == lltok::kw_volatile) {
7224 isVolatile = true;
7225 Lex.Lex();
7226 }
7227
7228 if (parseTypeAndValue(Val, Loc, PFS) ||
7229 parseToken(lltok::comma, "expected ',' after store operand") ||
7230 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7231 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7232 parseOptionalCommaAlign(Alignment, AteExtraComma))
7233 return true;
7234
7235 if (!Ptr->getType()->isPointerTy())
7236 return error(PtrLoc, "store operand must be a pointer");
7237 if (!Val->getType()->isFirstClassType())
7238 return error(Loc, "store operand must be a first class value");
7239 if (!cast<PointerType>(Ptr->getType())
7240 ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7241 return error(Loc, "stored value and pointer type do not match");
7242 if (isAtomic && !Alignment)
7243 return error(Loc, "atomic store must have explicit non-zero alignment");
7244 if (Ordering == AtomicOrdering::Acquire ||
7245 Ordering == AtomicOrdering::AcquireRelease)
7246 return error(Loc, "atomic store cannot use Acquire ordering");
7247 SmallPtrSet<Type *, 4> Visited;
7248 if (!Alignment && !Val->getType()->isSized(&Visited))
7249 return error(Loc, "storing unsized types is not allowed");
7250 if (!Alignment)
7251 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
7252
7253 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
7254 return AteExtraComma ? InstExtraComma : InstNormal;
7255}
7256
7257/// parseCmpXchg
7258/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7259/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
7260/// 'Align'?
7261int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
7262 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
7263 bool AteExtraComma = false;
7264 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
7265 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
7266 SyncScope::ID SSID = SyncScope::System;
7267 bool isVolatile = false;
7268 bool isWeak = false;
7269 MaybeAlign Alignment;
7270
7271 if (EatIfPresent(lltok::kw_weak))
7272 isWeak = true;
7273
7274 if (EatIfPresent(lltok::kw_volatile))
7275 isVolatile = true;
7276
7277 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7278 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7279 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
7280 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7281 parseTypeAndValue(New, NewLoc, PFS) ||
7282 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
7283 parseOrdering(FailureOrdering) ||
7284 parseOptionalCommaAlign(Alignment, AteExtraComma))
7285 return true;
7286
7287 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
7288 return tokError("invalid cmpxchg success ordering");
7289 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
7290 return tokError("invalid cmpxchg failure ordering");
7291 if (!Ptr->getType()->isPointerTy())
7292 return error(PtrLoc, "cmpxchg operand must be a pointer");
7293 if (!cast<PointerType>(Ptr->getType())
7294 ->isOpaqueOrPointeeTypeMatches(Cmp->getType()))
7295 return error(CmpLoc, "compare value and pointer type do not match");
7296 if (!cast<PointerType>(Ptr->getType())
7297 ->isOpaqueOrPointeeTypeMatches(New->getType()))
7298 return error(NewLoc, "new value and pointer type do not match");
7299 if (Cmp->getType() != New->getType())
7300 return error(NewLoc, "compare value and new value type do not match");
7301 if (!New->getType()->isFirstClassType())
7302 return error(NewLoc, "cmpxchg operand must be a first class value");
7303
7304 const Align DefaultAlignment(
7305 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7306 Cmp->getType()));
7307
7308 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
7309 Ptr, Cmp, New, Alignment.getValueOr(DefaultAlignment), SuccessOrdering,
7310 FailureOrdering, SSID);
7311 CXI->setVolatile(isVolatile);
7312 CXI->setWeak(isWeak);
7313
7314 Inst = CXI;
7315 return AteExtraComma ? InstExtraComma : InstNormal;
7316}
7317
7318/// parseAtomicRMW
7319/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7320/// 'singlethread'? AtomicOrdering
7321int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
7322 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7323 bool AteExtraComma = false;
7324 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7325 SyncScope::ID SSID = SyncScope::System;
7326 bool isVolatile = false;
7327 bool IsFP = false;
7328 AtomicRMWInst::BinOp Operation;
7329 MaybeAlign Alignment;
7330
7331 if (EatIfPresent(lltok::kw_volatile))
7332 isVolatile = true;
7333
7334 switch (Lex.getKind()) {
7335 default:
7336 return tokError("expected binary operation in atomicrmw");
7337 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7338 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7339 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7340 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7341 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7342 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7343 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7344 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7345 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7346 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7347 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
7348 case lltok::kw_fadd:
7349 Operation = AtomicRMWInst::FAdd;
7350 IsFP = true;
7351 break;
7352 case lltok::kw_fsub:
7353 Operation = AtomicRMWInst::FSub;
7354 IsFP = true;
7355 break;
7356 }
7357 Lex.Lex(); // Eat the operation.
7358
7359 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7360 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7361 parseTypeAndValue(Val, ValLoc, PFS) ||
7362 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
7363 parseOptionalCommaAlign(Alignment, AteExtraComma))
7364 return true;
7365
7366 if (Ordering == AtomicOrdering::Unordered)
7367 return tokError("atomicrmw cannot be unordered");
7368 if (!Ptr->getType()->isPointerTy())
7369 return error(PtrLoc, "atomicrmw operand must be a pointer");
7370 if (!cast<PointerType>(Ptr->getType())
7371 ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7372 return error(ValLoc, "atomicrmw value and pointer type do not match");
7373
7374 if (Operation == AtomicRMWInst::Xchg) {
7375 if (!Val->getType()->isIntegerTy() &&
7376 !Val->getType()->isFloatingPointTy()) {
7377 return error(ValLoc,
7378 "atomicrmw " + AtomicRMWInst::getOperationName(Operation) +
7379 " operand must be an integer or floating point type");
7380 }
7381 } else if (IsFP) {
7382 if (!Val->getType()->isFloatingPointTy()) {
7383 return error(ValLoc, "atomicrmw " +
7384 AtomicRMWInst::getOperationName(Operation) +
7385 " operand must be a floating point type");
7386 }
7387 } else {
7388 if (!Val->getType()->isIntegerTy()) {
7389 return error(ValLoc, "atomicrmw " +
7390 AtomicRMWInst::getOperationName(Operation) +
7391 " operand must be an integer");
7392 }
7393 }
7394
7395 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
7396 if (Size < 8 || (Size & (Size - 1)))
7397 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7398 " integer");
7399 const Align DefaultAlignment(
7400 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7401 Val->getType()));
7402 AtomicRMWInst *RMWI =
7403 new AtomicRMWInst(Operation, Ptr, Val,
7404 Alignment.getValueOr(DefaultAlignment), Ordering, SSID);
7405 RMWI->setVolatile(isVolatile);
7406 Inst = RMWI;
7407 return AteExtraComma ? InstExtraComma : InstNormal;
7408}
7409
7410/// parseFence
7411/// ::= 'fence' 'singlethread'? AtomicOrdering
7412int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
7413 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7414 SyncScope::ID SSID = SyncScope::System;
7415 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7416 return true;
7417
7418 if (Ordering == AtomicOrdering::Unordered)
7419 return tokError("fence cannot be unordered");
7420 if (Ordering == AtomicOrdering::Monotonic)
7421 return tokError("fence cannot be monotonic");
7422
7423 Inst = new FenceInst(Context, Ordering, SSID);
7424 return InstNormal;
7425}
7426
7427/// parseGetElementPtr
7428/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7429int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7430 Value *Ptr = nullptr;
7431 Value *Val = nullptr;
7432 LocTy Loc, EltLoc;
7433
7434 bool InBounds = EatIfPresent(lltok::kw_inbounds);
7435
7436 Type *Ty = nullptr;
7437 LocTy ExplicitTypeLoc = Lex.getLoc();
7438 if (parseType(Ty) ||
7439 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
7440 parseTypeAndValue(Ptr, Loc, PFS))
7441 return true;
7442
7443 Type *BaseType = Ptr->getType();
7444 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7445 if (!BasePointerType)
7446 return error(Loc, "base of getelementptr must be a pointer");
7447
7448 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
7449 return error(
7450 ExplicitTypeLoc,
7451 typeComparisonErrorMessage(
7452 "explicit pointee type doesn't match operand's pointee type", Ty,
7453 BasePointerType->getElementType()));
7454 }
7455
7456 SmallVector<Value*, 16> Indices;
7457 bool AteExtraComma = false;
7458 // GEP returns a vector of pointers if at least one of parameters is a vector.
7459 // All vector parameters should have the same vector width.
7460 ElementCount GEPWidth = BaseType->isVectorTy()
7461 ? cast<VectorType>(BaseType)->getElementCount()
7462 : ElementCount::getFixed(0);
7463
7464 while (EatIfPresent(lltok::comma)) {
7465 if (Lex.getKind() == lltok::MetadataVar) {
7466 AteExtraComma = true;
7467 break;
7468 }
7469 if (parseTypeAndValue(Val, EltLoc, PFS))
7470 return true;
7471 if (!Val->getType()->isIntOrIntVectorTy())
7472 return error(EltLoc, "getelementptr index must be an integer");
7473
7474 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
7475 ElementCount ValNumEl = ValVTy->getElementCount();
7476 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
7477 return error(
7478 EltLoc,
7479 "getelementptr vector index has a wrong number of elements");
7480 GEPWidth = ValNumEl;
7481 }
7482 Indices.push_back(Val);
7483 }
7484
7485 SmallPtrSet<Type*, 4> Visited;
7486 if (!Indices.empty() && !Ty->isSized(&Visited))
7487 return error(Loc, "base element of getelementptr must be sized");
7488
7489 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
7490 return error(Loc, "invalid getelementptr indices");
7491 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
7492 if (InBounds)
7493 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
7494 return AteExtraComma ? InstExtraComma : InstNormal;
7495}
7496
7497/// parseExtractValue
7498/// ::= 'extractvalue' TypeAndValue (',' uint32)+
7499int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
7500 Value *Val; LocTy Loc;
7501 SmallVector<unsigned, 4> Indices;
7502 bool AteExtraComma;
7503 if (parseTypeAndValue(Val, Loc, PFS) ||
7504 parseIndexList(Indices, AteExtraComma))
7505 return true;
7506
7507 if (!Val->getType()->isAggregateType())
7508 return error(Loc, "extractvalue operand must be aggregate type");
7509
7510 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
7511 return error(Loc, "invalid indices for extractvalue");
7512 Inst = ExtractValueInst::Create(Val, Indices);
7513 return AteExtraComma ? InstExtraComma : InstNormal;
7514}
7515
7516/// parseInsertValue
7517/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7518int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
7519 Value *Val0, *Val1; LocTy Loc0, Loc1;
7520 SmallVector<unsigned, 4> Indices;
7521 bool AteExtraComma;
7522 if (parseTypeAndValue(Val0, Loc0, PFS) ||
7523 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
7524 parseTypeAndValue(Val1, Loc1, PFS) ||
7525 parseIndexList(Indices, AteExtraComma))
7526 return true;
7527
7528 if (!Val0->getType()->isAggregateType())
7529 return error(Loc0, "insertvalue operand must be aggregate type");
7530
7531 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7532 if (!IndexedType)
7533 return error(Loc0, "invalid indices for insertvalue");
7534 if (IndexedType != Val1->getType())
7535 return error(Loc1, "insertvalue operand and field disagree in type: '" +
7536 getTypeString(Val1->getType()) + "' instead of '" +
7537 getTypeString(IndexedType) + "'");
7538 Inst = InsertValueInst::Create(Val0, Val1, Indices);
7539 return AteExtraComma ? InstExtraComma : InstNormal;
7540}
7541
7542//===----------------------------------------------------------------------===//
7543// Embedded metadata.
7544//===----------------------------------------------------------------------===//
7545
7546/// parseMDNodeVector
7547/// ::= { Element (',' Element)* }
7548/// Element
7549/// ::= 'null' | TypeAndValue
7550bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7551 if (parseToken(lltok::lbrace, "expected '{' here"))
7552 return true;
7553
7554 // Check for an empty list.
7555 if (EatIfPresent(lltok::rbrace))
7556 return false;
7557
7558 do {
7559 // Null is a special case since it is typeless.
7560 if (EatIfPresent(lltok::kw_null)) {
7561 Elts.push_back(nullptr);
7562 continue;
7563 }
7564
7565 Metadata *MD;
7566 if (parseMetadata(MD, nullptr))
7567 return true;
7568 Elts.push_back(MD);
7569 } while (EatIfPresent(lltok::comma));
7570
7571 return parseToken(lltok::rbrace, "expected end of metadata node");
7572}
7573
7574//===----------------------------------------------------------------------===//
7575// Use-list order directives.
7576//===----------------------------------------------------------------------===//
7577bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7578 SMLoc Loc) {
7579 if (V->use_empty())
7580 return error(Loc, "value has no uses");
7581
7582 unsigned NumUses = 0;
7583 SmallDenseMap<const Use *, unsigned, 16> Order;
7584 for (const Use &U : V->uses()) {
7585 if (++NumUses > Indexes.size())
7586 break;
7587 Order[&U] = Indexes[NumUses - 1];
7588 }
7589 if (NumUses < 2)
7590 return error(Loc, "value only has one use");
7591 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
7592 return error(Loc,
7593 "wrong number of indexes, expected " + Twine(V->getNumUses()));
7594
7595 V->sortUseList([&](const Use &L, const Use &R) {
7596 return Order.lookup(&L) < Order.lookup(&R);
7597 });
7598 return false;
7599}
7600
7601/// parseUseListOrderIndexes
7602/// ::= '{' uint32 (',' uint32)+ '}'
7603bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7604 SMLoc Loc = Lex.getLoc();
7605 if (parseToken(lltok::lbrace, "expected '{' here"))
7606 return true;
7607 if (Lex.getKind() == lltok::rbrace)
7608 return Lex.Error("expected non-empty list of uselistorder indexes");
7609
7610 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7611 // indexes should be distinct numbers in the range [0, size-1], and should
7612 // not be in order.
7613 unsigned Offset = 0;
7614 unsigned Max = 0;
7615 bool IsOrdered = true;
7616 assert(Indexes.empty() && "Expected empty order vector")((void)0);
7617 do {
7618 unsigned Index;
7619 if (parseUInt32(Index))
7620 return true;
7621
7622 // Update consistency checks.
7623 Offset += Index - Indexes.size();
7624 Max = std::max(Max, Index);
7625 IsOrdered &= Index == Indexes.size();
7626
7627 Indexes.push_back(Index);
7628 } while (EatIfPresent(lltok::comma));
7629
7630 if (parseToken(lltok::rbrace, "expected '}' here"))
7631 return true;
7632
7633 if (Indexes.size() < 2)
7634 return error(Loc, "expected >= 2 uselistorder indexes");
7635 if (Offset != 0 || Max >= Indexes.size())
7636 return error(Loc,
7637 "expected distinct uselistorder indexes in range [0, size)");
7638 if (IsOrdered)
7639 return error(Loc, "expected uselistorder indexes to change the order");
7640
7641 return false;
7642}
7643
7644/// parseUseListOrder
7645/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7646bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
7647 SMLoc Loc = Lex.getLoc();
7648 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7649 return true;
7650
7651 Value *V;
7652 SmallVector<unsigned, 16> Indexes;
7653 if (parseTypeAndValue(V, PFS) ||
7654 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
7655 parseUseListOrderIndexes(Indexes))
7656 return true;
7657
7658 return sortUseListOrder(V, Indexes, Loc);
7659}
7660
7661/// parseUseListOrderBB
7662/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7663bool LLParser::parseUseListOrderBB() {
7664 assert(Lex.getKind() == lltok::kw_uselistorder_bb)((void)0);
7665 SMLoc Loc = Lex.getLoc();
7666 Lex.Lex();
7667
7668 ValID Fn, Label;
7669 SmallVector<unsigned, 16> Indexes;
7670 if (parseValID(Fn, /*PFS=*/nullptr) ||
7671 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7672 parseValID(Label, /*PFS=*/nullptr) ||
7673 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7674 parseUseListOrderIndexes(Indexes))
7675 return true;
7676
7677 // Check the function.
7678 GlobalValue *GV;
7679 if (Fn.Kind == ValID::t_GlobalName)
7680 GV = M->getNamedValue(Fn.StrVal);
7681 else if (Fn.Kind == ValID::t_GlobalID)
7682 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7683 else
7684 return error(Fn.Loc, "expected function name in uselistorder_bb");
7685 if (!GV)
7686 return error(Fn.Loc,
7687 "invalid function forward reference in uselistorder_bb");
7688 auto *F = dyn_cast<Function>(GV);
7689 if (!F)
7690 return error(Fn.Loc, "expected function name in uselistorder_bb");
7691 if (F->isDeclaration())
7692 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
7693
7694 // Check the basic block.
7695 if (Label.Kind == ValID::t_LocalID)
7696 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
7697 if (Label.Kind != ValID::t_LocalName)
7698 return error(Label.Loc, "expected basic block name in uselistorder_bb");
7699 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
7700 if (!V)
7701 return error(Label.Loc, "invalid basic block in uselistorder_bb");
7702 if (!isa<BasicBlock>(V))
7703 return error(Label.Loc, "expected basic block in uselistorder_bb");
7704
7705 return sortUseListOrder(V, Indexes, Loc);
7706}
7707
7708/// ModuleEntry
7709/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7710/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7711bool LLParser::parseModuleEntry(unsigned ID) {
7712 assert(Lex.getKind() == lltok::kw_module)((void)0);
7713 Lex.Lex();
7714
7715 std::string Path;
7716 if (parseToken(lltok::colon, "expected ':' here") ||
7717 parseToken(lltok::lparen, "expected '(' here") ||
7718 parseToken(lltok::kw_path, "expected 'path' here") ||
7719 parseToken(lltok::colon, "expected ':' here") ||
7720 parseStringConstant(Path) ||
7721 parseToken(lltok::comma, "expected ',' here") ||
7722 parseToken(lltok::kw_hash, "expected 'hash' here") ||
7723 parseToken(lltok::colon, "expected ':' here") ||
7724 parseToken(lltok::lparen, "expected '(' here"))
7725 return true;
7726
7727 ModuleHash Hash;
7728 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
7729 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
7730 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
7731 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
7732 parseUInt32(Hash[4]))
7733 return true;
7734
7735 if (parseToken(lltok::rparen, "expected ')' here") ||
7736 parseToken(lltok::rparen, "expected ')' here"))
7737 return true;
7738
7739 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7740 ModuleIdMap[ID] = ModuleEntry->first();
7741
7742 return false;
7743}
7744
7745/// TypeIdEntry
7746/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7747bool LLParser::parseTypeIdEntry(unsigned ID) {
7748 assert(Lex.getKind() == lltok::kw_typeid)((void)0);
7749 Lex.Lex();
7750
7751 std::string Name;
7752 if (parseToken(lltok::colon, "expected ':' here") ||
7753 parseToken(lltok::lparen, "expected '(' here") ||
7754 parseToken(lltok::kw_name, "expected 'name' here") ||
7755 parseToken(lltok::colon, "expected ':' here") ||
7756 parseStringConstant(Name))
7757 return true;
7758
7759 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7760 if (parseToken(lltok::comma, "expected ',' here") ||
7761 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
7762 return true;
7763
7764 // Check if this ID was forward referenced, and if so, update the
7765 // corresponding GUIDs.
7766 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7767 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7768 for (auto TIDRef : FwdRefTIDs->second) {
7769 assert(!*TIDRef.first &&((void)0)
7770 "Forward referenced type id GUID expected to be 0")((void)0);
7771 *TIDRef.first = GlobalValue::getGUID(Name);
7772 }
7773 ForwardRefTypeIds.erase(FwdRefTIDs);
7774 }
7775
7776 return false;
7777}
7778
7779/// TypeIdSummary
7780/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7781bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
7782 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
7783 parseToken(lltok::colon, "expected ':' here") ||
7784 parseToken(lltok::lparen, "expected '(' here") ||
7785 parseTypeTestResolution(TIS.TTRes))
7786 return true;
7787
7788 if (EatIfPresent(lltok::comma)) {
7789 // Expect optional wpdResolutions field
7790 if (parseOptionalWpdResolutions(TIS.WPDRes))
7791 return true;
7792 }
7793
7794 if (parseToken(lltok::rparen, "expected ')' here"))
7795 return true;
7796
7797 return false;
7798}
7799
7800static ValueInfo EmptyVI =
7801 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7802
7803/// TypeIdCompatibleVtableEntry
7804/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
7805/// TypeIdCompatibleVtableInfo
7806/// ')'
7807bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
7808 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable)((void)0);
7809 Lex.Lex();
7810
7811 std::string Name;
7812 if (parseToken(lltok::colon, "expected ':' here") ||
7813 parseToken(lltok::lparen, "expected '(' here") ||
7814 parseToken(lltok::kw_name, "expected 'name' here") ||
7815 parseToken(lltok::colon, "expected ':' here") ||
7816 parseStringConstant(Name))
7817 return true;
7818
7819 TypeIdCompatibleVtableInfo &TI =
7820 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
7821 if (parseToken(lltok::comma, "expected ',' here") ||
7822 parseToken(lltok::kw_summary, "expected 'summary' here") ||
7823 parseToken(lltok::colon, "expected ':' here") ||
7824 parseToken(lltok::lparen, "expected '(' here"))
7825 return true;
7826
7827 IdToIndexMapType IdToIndexMap;
7828 // parse each call edge
7829 do {
7830 uint64_t Offset;
7831 if (parseToken(lltok::lparen, "expected '(' here") ||
7832 parseToken(lltok::kw_offset, "expected 'offset' here") ||
7833 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
7834 parseToken(lltok::comma, "expected ',' here"))
7835 return true;
7836
7837 LocTy Loc = Lex.getLoc();
7838 unsigned GVId;
7839 ValueInfo VI;
7840 if (parseGVReference(VI, GVId))
7841 return true;
7842
7843 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
7844 // forward reference. We will save the location of the ValueInfo needing an
7845 // update, but can only do so once the std::vector is finalized.
7846 if (VI == EmptyVI)
7847 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
7848 TI.push_back({Offset, VI});
7849
7850 if (parseToken(lltok::rparen, "expected ')' in call"))
7851 return true;
7852 } while (EatIfPresent(lltok::comma));
7853
7854 // Now that the TI vector is finalized, it is safe to save the locations
7855 // of any forward GV references that need updating later.
7856 for (auto I : IdToIndexMap) {
7857 auto &Infos = ForwardRefValueInfos[I.first];
7858 for (auto P : I.second) {
7859 assert(TI[P.first].VTableVI == EmptyVI &&((void)0)
7860 "Forward referenced ValueInfo expected to be empty")((void)0);
7861 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
7862 }
7863 }
7864
7865 if (parseToken(lltok::rparen, "expected ')' here") ||
7866 parseToken(lltok::rparen, "expected ')' here"))
7867 return true;
7868
7869 // Check if this ID was forward referenced, and if so, update the
7870 // corresponding GUIDs.
7871 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7872 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7873 for (auto TIDRef : FwdRefTIDs->second) {
7874 assert(!*TIDRef.first &&((void)0)
7875 "Forward referenced type id GUID expected to be 0")((void)0);
7876 *TIDRef.first = GlobalValue::getGUID(Name);
7877 }
7878 ForwardRefTypeIds.erase(FwdRefTIDs);
7879 }
7880
7881 return false;
7882}
7883
7884/// TypeTestResolution
7885/// ::= 'typeTestRes' ':' '(' 'kind' ':'
7886/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7887/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7888/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7889/// [',' 'inlinesBits' ':' UInt64]? ')'
7890bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
7891 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7892 parseToken(lltok::colon, "expected ':' here") ||
7893 parseToken(lltok::lparen, "expected '(' here") ||
7894 parseToken(lltok::kw_kind, "expected 'kind' here") ||
7895 parseToken(lltok::colon, "expected ':' here"))
7896 return true;
7897
7898 switch (Lex.getKind()) {
7899 case lltok::kw_unknown:
7900 TTRes.TheKind = TypeTestResolution::Unknown;
7901 break;
7902 case lltok::kw_unsat:
7903 TTRes.TheKind = TypeTestResolution::Unsat;
7904 break;
7905 case lltok::kw_byteArray:
7906 TTRes.TheKind = TypeTestResolution::ByteArray;
7907 break;
7908 case lltok::kw_inline:
7909 TTRes.TheKind = TypeTestResolution::Inline;
7910 break;
7911 case lltok::kw_single:
7912 TTRes.TheKind = TypeTestResolution::Single;
7913 break;
7914 case lltok::kw_allOnes:
7915 TTRes.TheKind = TypeTestResolution::AllOnes;
7916 break;
7917 default:
7918 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7919 }
7920 Lex.Lex();
7921
7922 if (parseToken(lltok::comma, "expected ',' here") ||
7923 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7924 parseToken(lltok::colon, "expected ':' here") ||
7925 parseUInt32(TTRes.SizeM1BitWidth))
7926 return true;
7927
7928 // parse optional fields
7929 while (EatIfPresent(lltok::comma)) {
7930 switch (Lex.getKind()) {
7931 case lltok::kw_alignLog2:
7932 Lex.Lex();
7933 if (parseToken(lltok::colon, "expected ':'") ||
7934 parseUInt64(TTRes.AlignLog2))
7935 return true;
7936 break;
7937 case lltok::kw_sizeM1:
7938 Lex.Lex();
7939 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
7940 return true;
7941 break;
7942 case lltok::kw_bitMask: {
7943 unsigned Val;
7944 Lex.Lex();
7945 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
7946 return true;
7947 assert(Val <= 0xff)((void)0);
7948 TTRes.BitMask = (uint8_t)Val;
7949 break;
7950 }
7951 case lltok::kw_inlineBits:
7952 Lex.Lex();
7953 if (parseToken(lltok::colon, "expected ':'") ||
7954 parseUInt64(TTRes.InlineBits))
7955 return true;
7956 break;
7957 default:
7958 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
7959 }
7960 }
7961
7962 if (parseToken(lltok::rparen, "expected ')' here"))
7963 return true;
7964
7965 return false;
7966}
7967
7968/// OptionalWpdResolutions
7969/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7970/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7971bool LLParser::parseOptionalWpdResolutions(
7972 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7973 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7974 parseToken(lltok::colon, "expected ':' here") ||
7975 parseToken(lltok::lparen, "expected '(' here"))
7976 return true;
7977
7978 do {
7979 uint64_t Offset;
7980 WholeProgramDevirtResolution WPDRes;
7981 if (parseToken(lltok::lparen, "expected '(' here") ||
7982 parseToken(lltok::kw_offset, "expected 'offset' here") ||
7983 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
7984 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
7985 parseToken(lltok::rparen, "expected ')' here"))
7986 return true;
7987 WPDResMap[Offset] = WPDRes;
7988 } while (EatIfPresent(lltok::comma));
7989
7990 if (parseToken(lltok::rparen, "expected ')' here"))
7991 return true;
7992
7993 return false;
7994}
7995
7996/// WpdRes
7997/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7998/// [',' OptionalResByArg]? ')'
7999/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
8000/// ',' 'singleImplName' ':' STRINGCONSTANT ','
8001/// [',' OptionalResByArg]? ')'
8002/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
8003/// [',' OptionalResByArg]? ')'
8004bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
8005 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
8006 parseToken(lltok::colon, "expected ':' here") ||
8007 parseToken(lltok::lparen, "expected '(' here") ||
8008 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8009 parseToken(lltok::colon, "expected ':' here"))
8010 return true;
8011
8012 switch (Lex.getKind()) {
8013 case lltok::kw_indir:
8014 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
8015 break;
8016 case lltok::kw_singleImpl:
8017 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
8018 break;
8019 case lltok::kw_branchFunnel:
8020 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
8021 break;
8022 default:
8023 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8024 }
8025 Lex.Lex();
8026
8027 // parse optional fields
8028 while (EatIfPresent(lltok::comma)) {
8029 switch (Lex.getKind()) {
8030 case lltok::kw_singleImplName:
8031 Lex.Lex();
8032 if (parseToken(lltok::colon, "expected ':' here") ||
8033 parseStringConstant(WPDRes.SingleImplName))
8034 return true;
8035 break;
8036 case lltok::kw_resByArg:
8037 if (parseOptionalResByArg(WPDRes.ResByArg))
8038 return true;
8039 break;
8040 default:
8041 return error(Lex.getLoc(),
8042 "expected optional WholeProgramDevirtResolution field");
8043 }
8044 }
8045
8046 if (parseToken(lltok::rparen, "expected ')' here"))
8047 return true;
8048
8049 return false;
8050}
8051
8052/// OptionalResByArg
8053/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8054/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8055/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8056/// 'virtualConstProp' )
8057/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8058/// [',' 'bit' ':' UInt32]? ')'
8059bool LLParser::parseOptionalResByArg(
8060 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
8061 &ResByArg) {
8062 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
8063 parseToken(lltok::colon, "expected ':' here") ||
8064 parseToken(lltok::lparen, "expected '(' here"))
8065 return true;
8066
8067 do {
8068 std::vector<uint64_t> Args;
8069 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
8070 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
8071 parseToken(lltok::colon, "expected ':' here") ||
8072 parseToken(lltok::lparen, "expected '(' here") ||
8073 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8074 parseToken(lltok::colon, "expected ':' here"))
8075 return true;
8076
8077 WholeProgramDevirtResolution::ByArg ByArg;
8078 switch (Lex.getKind()) {
8079 case lltok::kw_indir:
8080 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
8081 break;
8082 case lltok::kw_uniformRetVal:
8083 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
8084 break;
8085 case lltok::kw_uniqueRetVal:
8086 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
8087 break;
8088 case lltok::kw_virtualConstProp:
8089 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
8090 break;
8091 default:
8092 return error(Lex.getLoc(),
8093 "unexpected WholeProgramDevirtResolution::ByArg kind");
8094 }
8095 Lex.Lex();
8096
8097 // parse optional fields
8098 while (EatIfPresent(lltok::comma)) {
8099 switch (Lex.getKind()) {
8100 case lltok::kw_info:
8101 Lex.Lex();
8102 if (parseToken(lltok::colon, "expected ':' here") ||
8103 parseUInt64(ByArg.Info))
8104 return true;
8105 break;
8106 case lltok::kw_byte:
8107 Lex.Lex();
8108 if (parseToken(lltok::colon, "expected ':' here") ||
8109 parseUInt32(ByArg.Byte))
8110 return true;
8111 break;
8112 case lltok::kw_bit:
8113 Lex.Lex();
8114 if (parseToken(lltok::colon, "expected ':' here") ||
8115 parseUInt32(ByArg.Bit))
8116 return true;
8117 break;
8118 default:
8119 return error(Lex.getLoc(),
8120 "expected optional whole program devirt field");
8121 }
8122 }
8123
8124 if (parseToken(lltok::rparen, "expected ')' here"))
8125 return true;
8126
8127 ResByArg[Args] = ByArg;
8128 } while (EatIfPresent(lltok::comma));
8129
8130 if (parseToken(lltok::rparen, "expected ')' here"))
8131 return true;
8132
8133 return false;
8134}
8135
8136/// OptionalResByArg
8137/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
8138bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
8139 if (parseToken(lltok::kw_args, "expected 'args' here") ||
8140 parseToken(lltok::colon, "expected ':' here") ||
8141 parseToken(lltok::lparen, "expected '(' here"))
8142 return true;
8143
8144 do {
8145 uint64_t Val;
8146 if (parseUInt64(Val))
8147 return true;
8148 Args.push_back(Val);
8149 } while (EatIfPresent(lltok::comma));
8150
8151 if (parseToken(lltok::rparen, "expected ')' here"))
8152 return true;
8153
8154 return false;
8155}
8156
8157static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
8158
8159static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
8160 bool ReadOnly = Fwd->isReadOnly();
8161 bool WriteOnly = Fwd->isWriteOnly();
8162 assert(!(ReadOnly && WriteOnly))((void)0);
8163 *Fwd = Resolved;
8164 if (ReadOnly)
8165 Fwd->setReadOnly();
8166 if (WriteOnly)
8167 Fwd->setWriteOnly();
8168}
8169
8170/// Stores the given Name/GUID and associated summary into the Index.
8171/// Also updates any forward references to the associated entry ID.
8172void LLParser::addGlobalValueToIndex(
8173 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
8174 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
8175 // First create the ValueInfo utilizing the Name or GUID.
8176 ValueInfo VI;
8177 if (GUID != 0) {
8178 assert(Name.empty())((void)0);
8179 VI = Index->getOrInsertValueInfo(GUID);
8180 } else {
8181 assert(!Name.empty())((void)0);
8182 if (M) {
8183 auto *GV = M->getNamedValue(Name);
8184 assert(GV)((void)0);
8185 VI = Index->getOrInsertValueInfo(GV);
8186 } else {
8187 assert(((void)0)
8188 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&((void)0)
8189 "Need a source_filename to compute GUID for local")((void)0);
8190 GUID = GlobalValue::getGUID(
8191 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
8192 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
8193 }
8194 }
8195
8196 // Resolve forward references from calls/refs
8197 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
8198 if (FwdRefVIs != ForwardRefValueInfos.end()) {
8199 for (auto VIRef : FwdRefVIs->second) {
8200 assert(VIRef.first->getRef() == FwdVIRef &&((void)0)
8201 "Forward referenced ValueInfo expected to be empty")((void)0);
8202 resolveFwdRef(VIRef.first, VI);
8203 }
8204 ForwardRefValueInfos.erase(FwdRefVIs);
8205 }
8206
8207 // Resolve forward references from aliases
8208 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
8209 if (FwdRefAliasees != ForwardRefAliasees.end()) {
8210 for (auto AliaseeRef : FwdRefAliasees->second) {
8211 assert(!AliaseeRef.first->hasAliasee() &&((void)0)
8212 "Forward referencing alias already has aliasee")((void)0);
8213 assert(Summary && "Aliasee must be a definition")((void)0);
8214 AliaseeRef.first->setAliasee(VI, Summary.get());
8215 }
8216 ForwardRefAliasees.erase(FwdRefAliasees);
8217 }
8218
8219 // Add the summary if one was provided.
8220 if (Summary)
8221 Index->addGlobalValueSummary(VI, std::move(Summary));
8222
8223 // Save the associated ValueInfo for use in later references by ID.
8224 if (ID == NumberedValueInfos.size())
8225 NumberedValueInfos.push_back(VI);
8226 else {
8227 // Handle non-continuous numbers (to make test simplification easier).
8228 if (ID > NumberedValueInfos.size())
8229 NumberedValueInfos.resize(ID + 1);
8230 NumberedValueInfos[ID] = VI;
8231 }
8232}
8233
8234/// parseSummaryIndexFlags
8235/// ::= 'flags' ':' UInt64
8236bool LLParser::parseSummaryIndexFlags() {
8237 assert(Lex.getKind() == lltok::kw_flags)((void)0);
8238 Lex.Lex();
8239
8240 if (parseToken(lltok::colon, "expected ':' here"))
8241 return true;
8242 uint64_t Flags;
8243 if (parseUInt64(Flags))
8244 return true;
8245 if (Index)
8246 Index->setFlags(Flags);
8247 return false;
8248}
8249
8250/// parseBlockCount
8251/// ::= 'blockcount' ':' UInt64
8252bool LLParser::parseBlockCount() {
8253 assert(Lex.getKind() == lltok::kw_blockcount)((void)0);
8254 Lex.Lex();
8255
8256 if (parseToken(lltok::colon, "expected ':' here"))
8257 return true;
8258 uint64_t BlockCount;
8259 if (parseUInt64(BlockCount))
8260 return true;
8261 if (Index)
8262 Index->setBlockCount(BlockCount);
8263 return false;
8264}
8265
8266/// parseGVEntry
8267/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
8268/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
8269/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
8270bool LLParser::parseGVEntry(unsigned ID) {
8271 assert(Lex.getKind() == lltok::kw_gv)((void)0);
8272 Lex.Lex();
8273
8274 if (parseToken(lltok::colon, "expected ':' here") ||
8275 parseToken(lltok::lparen, "expected '(' here"))
8276 return true;
8277
8278 std::string Name;
8279 GlobalValue::GUID GUID = 0;
8280 switch (Lex.getKind()) {
8281 case lltok::kw_name:
8282 Lex.Lex();
8283 if (parseToken(lltok::colon, "expected ':' here") ||
8284 parseStringConstant(Name))
8285 return true;
8286 // Can't create GUID/ValueInfo until we have the linkage.
8287 break;
8288 case lltok::kw_guid:
8289 Lex.Lex();
8290 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
8291 return true;
8292 break;
8293 default:
8294 return error(Lex.getLoc(), "expected name or guid tag");
8295 }
8296
8297 if (!EatIfPresent(lltok::comma)) {
8298 // No summaries. Wrap up.
8299 if (parseToken(lltok::rparen, "expected ')' here"))
8300 return true;
8301 // This was created for a call to an external or indirect target.
8302 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8303 // created for indirect calls with VP. A Name with no GUID came from
8304 // an external definition. We pass ExternalLinkage since that is only
8305 // used when the GUID must be computed from Name, and in that case
8306 // the symbol must have external linkage.
8307 addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
8308 nullptr);
8309 return false;
8310 }
8311
8312 // Have a list of summaries
8313 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
8314 parseToken(lltok::colon, "expected ':' here") ||
8315 parseToken(lltok::lparen, "expected '(' here"))
8316 return true;
8317 do {
8318 switch (Lex.getKind()) {
8319 case lltok::kw_function:
8320 if (parseFunctionSummary(Name, GUID, ID))
8321 return true;
8322 break;
8323 case lltok::kw_variable:
8324 if (parseVariableSummary(Name, GUID, ID))
8325 return true;
8326 break;
8327 case lltok::kw_alias:
8328 if (parseAliasSummary(Name, GUID, ID))
8329 return true;
8330 break;
8331 default:
8332 return error(Lex.getLoc(), "expected summary type");
8333 }
8334 } while (EatIfPresent(lltok::comma));
8335
8336 if (parseToken(lltok::rparen, "expected ')' here") ||
8337 parseToken(lltok::rparen, "expected ')' here"))
8338 return true;
8339
8340 return false;
8341}
8342
8343/// FunctionSummary
8344/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8345/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8346/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
8347/// [',' OptionalRefs]? ')'
8348bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8349 unsigned ID) {
8350 assert(Lex.getKind() == lltok::kw_function)((void)0);
8351 Lex.Lex();
8352
8353 StringRef ModulePath;
8354 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8355 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8356 /*NotEligibleToImport=*/false,
8357 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8358 unsigned InstCount;
8359 std::vector<FunctionSummary::EdgeTy> Calls;
8360 FunctionSummary::TypeIdInfo TypeIdInfo;
8361 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
8362 std::vector<ValueInfo> Refs;
8363 // Default is all-zeros (conservative values).
8364 FunctionSummary::FFlags FFlags = {};
8365 if (parseToken(lltok::colon, "expected ':' here") ||
8366 parseToken(lltok::lparen, "expected '(' here") ||
8367 parseModuleReference(ModulePath) ||
8368 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8369 parseToken(lltok::comma, "expected ',' here") ||
8370 parseToken(lltok::kw_insts, "expected 'insts' here") ||
8371 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
8372 return true;
8373
8374 // parse optional fields
8375 while (EatIfPresent(lltok::comma)) {
8376 switch (Lex.getKind()) {
8377 case lltok::kw_funcFlags:
8378 if (parseOptionalFFlags(FFlags))
8379 return true;
8380 break;
8381 case lltok::kw_calls:
8382 if (parseOptionalCalls(Calls))
8383 return true;
8384 break;
8385 case lltok::kw_typeIdInfo:
8386 if (parseOptionalTypeIdInfo(TypeIdInfo))
8387 return true;
8388 break;
8389 case lltok::kw_refs:
8390 if (parseOptionalRefs(Refs))
8391 return true;
8392 break;
8393 case lltok::kw_params:
8394 if (parseOptionalParamAccesses(ParamAccesses))
8395 return true;
8396 break;
8397 default:
8398 return error(Lex.getLoc(), "expected optional function summary field");
8399 }
8400 }
8401
8402 if (parseToken(lltok::rparen, "expected ')' here"))
8403 return true;
8404
8405 auto FS = std::make_unique<FunctionSummary>(
8406 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8407 std::move(Calls), std::move(TypeIdInfo.TypeTests),
8408 std::move(TypeIdInfo.TypeTestAssumeVCalls),
8409 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8410 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8411 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
8412 std::move(ParamAccesses));
8413
8414 FS->setModulePath(ModulePath);
8415
8416 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8417 ID, std::move(FS));
8418
8419 return false;
8420}
8421
8422/// VariableSummary
8423/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8424/// [',' OptionalRefs]? ')'
8425bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8426 unsigned ID) {
8427 assert(Lex.getKind() == lltok::kw_variable)((void)0);
8428 Lex.Lex();
8429
8430 StringRef ModulePath;
8431 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8432 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8433 /*NotEligibleToImport=*/false,
8434 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8435 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8436 /* WriteOnly */ false,
8437 /* Constant */ false,
8438 GlobalObject::VCallVisibilityPublic);
8439 std::vector<ValueInfo> Refs;
8440 VTableFuncList VTableFuncs;
8441 if (parseToken(lltok::colon, "expected ':' here") ||
8442 parseToken(lltok::lparen, "expected '(' here") ||
8443 parseModuleReference(ModulePath) ||
8444 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8445 parseToken(lltok::comma, "expected ',' here") ||
8446 parseGVarFlags(GVarFlags))
8447 return true;
8448
8449 // parse optional fields
8450 while (EatIfPresent(lltok::comma)) {
8451 switch (Lex.getKind()) {
8452 case lltok::kw_vTableFuncs:
8453 if (parseOptionalVTableFuncs(VTableFuncs))
8454 return true;
8455 break;
8456 case lltok::kw_refs:
8457 if (parseOptionalRefs(Refs))
8458 return true;
8459 break;
8460 default:
8461 return error(Lex.getLoc(), "expected optional variable summary field");
8462 }
8463 }
8464
8465 if (parseToken(lltok::rparen, "expected ')' here"))
8466 return true;
8467
8468 auto GS =
8469 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
8470
8471 GS->setModulePath(ModulePath);
8472 GS->setVTableFuncs(std::move(VTableFuncs));
8473
8474 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8475 ID, std::move(GS));
8476
8477 return false;
8478}
8479
8480/// AliasSummary
8481/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8482/// 'aliasee' ':' GVReference ')'
8483bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
8484 unsigned ID) {
8485 assert(Lex.getKind() == lltok::kw_alias)((void)0);
8486 LocTy Loc = Lex.getLoc();
8487 Lex.Lex();
8488
8489 StringRef ModulePath;
8490 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8491 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8492 /*NotEligibleToImport=*/false,
8493 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8494 if (parseToken(lltok::colon, "expected ':' here") ||
8495 parseToken(lltok::lparen, "expected '(' here") ||
8496 parseModuleReference(ModulePath) ||
8497 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8498 parseToken(lltok::comma, "expected ',' here") ||
8499 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
8500 parseToken(lltok::colon, "expected ':' here"))
8501 return true;
8502
8503 ValueInfo AliaseeVI;
8504 unsigned GVId;
8505 if (parseGVReference(AliaseeVI, GVId))
8506 return true;
8507
8508 if (parseToken(lltok::rparen, "expected ')' here"))
8509 return true;
8510
8511 auto AS = std::make_unique<AliasSummary>(GVFlags);
8512
8513 AS->setModulePath(ModulePath);
8514
8515 // Record forward reference if the aliasee is not parsed yet.
8516 if (AliaseeVI.getRef() == FwdVIRef) {
8517 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
8518 } else {
8519 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
8520 assert(Summary && "Aliasee must be a definition")((void)0);
8521 AS->setAliasee(AliaseeVI, Summary);
8522 }
8523
8524 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8525 ID, std::move(AS));
8526
8527 return false;
8528}
8529
8530/// Flag
8531/// ::= [0|1]
8532bool LLParser::parseFlag(unsigned &Val) {
8533 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
8534 return tokError("expected integer");
8535 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
8536 Lex.Lex();
8537 return false;
8538}
8539
8540/// OptionalFFlags
8541/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8542/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8543/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
8544/// [',' 'noInline' ':' Flag]? ')'
8545/// [',' 'alwaysInline' ':' Flag]? ')'
8546
8547bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8548 assert(Lex.getKind() == lltok::kw_funcFlags)((void)0);
8549 Lex.Lex();
8550
8551 if (parseToken(lltok::colon, "expected ':' in funcFlags") |
8552 parseToken(lltok::lparen, "expected '(' in funcFlags"))
8553 return true;
8554
8555 do {
8556 unsigned Val = 0;
8557 switch (Lex.getKind()) {
8558 case lltok::kw_readNone:
8559 Lex.Lex();
8560 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8561 return true;
8562 FFlags.ReadNone = Val;
8563 break;
8564 case lltok::kw_readOnly:
8565 Lex.Lex();
8566 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8567 return true;
8568 FFlags.ReadOnly = Val;
8569 break;
8570 case lltok::kw_noRecurse:
8571 Lex.Lex();
8572 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8573 return true;
8574 FFlags.NoRecurse = Val;
8575 break;
8576 case lltok::kw_returnDoesNotAlias:
8577 Lex.Lex();
8578 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8579 return true;
8580 FFlags.ReturnDoesNotAlias = Val;
8581 break;
8582 case lltok::kw_noInline:
8583 Lex.Lex();
8584 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8585 return true;
8586 FFlags.NoInline = Val;
8587 break;
8588 case lltok::kw_alwaysInline:
8589 Lex.Lex();
8590 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8591 return true;
8592 FFlags.AlwaysInline = Val;
8593 break;
8594 default:
8595 return error(Lex.getLoc(), "expected function flag type");
8596 }
8597 } while (EatIfPresent(lltok::comma));
8598
8599 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
8600 return true;
8601
8602 return false;
8603}
8604
8605/// OptionalCalls
8606/// := 'calls' ':' '(' Call [',' Call]* ')'
8607/// Call ::= '(' 'callee' ':' GVReference
8608/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8609bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8610 assert(Lex.getKind() == lltok::kw_calls)((void)0);
8611 Lex.Lex();
8612
8613 if (parseToken(lltok::colon, "expected ':' in calls") |
8614 parseToken(lltok::lparen, "expected '(' in calls"))
8615 return true;
8616
8617 IdToIndexMapType IdToIndexMap;
8618 // parse each call edge
8619 do {
8620 ValueInfo VI;
8621 if (parseToken(lltok::lparen, "expected '(' in call") ||
8622 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
8623 parseToken(lltok::colon, "expected ':'"))
8624 return true;
8625
8626 LocTy Loc = Lex.getLoc();
8627 unsigned GVId;
8628 if (parseGVReference(VI, GVId))
8629 return true;
8630
8631 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
8632 unsigned RelBF = 0;
8633 if (EatIfPresent(lltok::comma)) {
8634 // Expect either hotness or relbf
8635 if (EatIfPresent(lltok::kw_hotness)) {
8636 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
8637 return true;
8638 } else {
8639 if (parseToken(lltok::kw_relbf, "expected relbf") ||
8640 parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
8641 return true;
8642 }
8643 }
8644 // Keep track of the Call array index needing a forward reference.
8645 // We will save the location of the ValueInfo needing an update, but
8646 // can only do so once the std::vector is finalized.
8647 if (VI.getRef() == FwdVIRef)
8648 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8649 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8650
8651 if (parseToken(lltok::rparen, "expected ')' in call"))
8652 return true;
8653 } while (EatIfPresent(lltok::comma));
8654
8655 // Now that the Calls vector is finalized, it is safe to save the locations
8656 // of any forward GV references that need updating later.
8657 for (auto I : IdToIndexMap) {
8658 auto &Infos = ForwardRefValueInfos[I.first];
8659 for (auto P : I.second) {
8660 assert(Calls[P.first].first.getRef() == FwdVIRef &&((void)0)
8661 "Forward referenced ValueInfo expected to be empty")((void)0);
8662 Infos.emplace_back(&Calls[P.first].first, P.second);
8663 }
8664 }
8665
8666 if (parseToken(lltok::rparen, "expected ')' in calls"))
8667 return true;
8668
8669 return false;
8670}
8671
8672/// Hotness
8673/// := ('unknown'|'cold'|'none'|'hot'|'critical')
8674bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
8675 switch (Lex.getKind()) {
8676 case lltok::kw_unknown:
8677 Hotness = CalleeInfo::HotnessType::Unknown;
8678 break;
8679 case lltok::kw_cold:
8680 Hotness = CalleeInfo::HotnessType::Cold;
8681 break;
8682 case lltok::kw_none:
8683 Hotness = CalleeInfo::HotnessType::None;
8684 break;
8685 case lltok::kw_hot:
8686 Hotness = CalleeInfo::HotnessType::Hot;
8687 break;
8688 case lltok::kw_critical:
8689 Hotness = CalleeInfo::HotnessType::Critical;
8690 break;
8691 default:
8692 return error(Lex.getLoc(), "invalid call edge hotness");
8693 }
8694 Lex.Lex();
8695 return false;
8696}
8697
8698/// OptionalVTableFuncs
8699/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8700/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
8701bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
8702 assert(Lex.getKind() == lltok::kw_vTableFuncs)((void)0);
8703 Lex.Lex();
8704
8705 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") |
8706 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
8707 return true;
8708
8709 IdToIndexMapType IdToIndexMap;
8710 // parse each virtual function pair
8711 do {
8712 ValueInfo VI;
8713 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
8714 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
8715 parseToken(lltok::colon, "expected ':'"))
8716 return true;
8717
8718 LocTy Loc = Lex.getLoc();
8719 unsigned GVId;
8720 if (parseGVReference(VI, GVId))
8721 return true;
8722
8723 uint64_t Offset;
8724 if (parseToken(lltok::comma, "expected comma") ||
8725 parseToken(lltok::kw_offset, "expected offset") ||
8726 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
8727 return true;
8728
8729 // Keep track of the VTableFuncs array index needing a forward reference.
8730 // We will save the location of the ValueInfo needing an update, but
8731 // can only do so once the std::vector is finalized.
8732 if (VI == EmptyVI)
8733 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
8734 VTableFuncs.push_back({VI, Offset});
8735
8736 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
8737 return true;
8738 } while (EatIfPresent(lltok::comma));
8739
8740 // Now that the VTableFuncs vector is finalized, it is safe to save the
8741 // locations of any forward GV references that need updating later.
8742 for (auto I : IdToIndexMap) {
8743 auto &Infos = ForwardRefValueInfos[I.first];
8744 for (auto P : I.second) {
8745 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&((void)0)
8746 "Forward referenced ValueInfo expected to be empty")((void)0);
8747 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
8748 }
8749 }
8750
8751 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
8752 return true;
8753
8754 return false;
8755}
8756
8757/// ParamNo := 'param' ':' UInt64
8758bool LLParser::parseParamNo(uint64_t &ParamNo) {
8759 if (parseToken(lltok::kw_param, "expected 'param' here") ||
8760 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
8761 return true;
8762 return false;
8763}
8764
8765/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
8766bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
8767 APSInt Lower;
8768 APSInt Upper;
8769 auto ParseAPSInt = [&](APSInt &Val) {
8770 if (Lex.getKind() != lltok::APSInt)
8771 return tokError("expected integer");
8772 Val = Lex.getAPSIntVal();
8773 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
8774 Val.setIsSigned(true);
8775 Lex.Lex();
8776 return false;
8777 };
8778 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
8779 parseToken(lltok::colon, "expected ':' here") ||
8780 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
8781 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
8782 parseToken(lltok::rsquare, "expected ']' here"))
8783 return true;
8784
8785 ++Upper;
8786 Range =
8787 (Lower == Upper && !Lower.isMaxValue())
8788 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
8789 : ConstantRange(Lower, Upper);
8790
8791 return false;
8792}
8793
8794/// ParamAccessCall
8795/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
8796bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
8797 IdLocListType &IdLocList) {
8798 if (parseToken(lltok::lparen, "expected '(' here") ||
8799 parseToken(lltok::kw_callee, "expected 'callee' here") ||
8800 parseToken(lltok::colon, "expected ':' here"))
8801 return true;
8802
8803 unsigned GVId;
8804 ValueInfo VI;
8805 LocTy Loc = Lex.getLoc();
8806 if (parseGVReference(VI, GVId))
8807 return true;
8808
8809 Call.Callee = VI;
8810 IdLocList.emplace_back(GVId, Loc);
8811
8812 if (parseToken(lltok::comma, "expected ',' here") ||
8813 parseParamNo(Call.ParamNo) ||
8814 parseToken(lltok::comma, "expected ',' here") ||
8815 parseParamAccessOffset(Call.Offsets))
8816 return true;
8817
8818 if (parseToken(lltok::rparen, "expected ')' here"))
8819 return true;
8820
8821 return false;
8822}
8823
8824/// ParamAccess
8825/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
8826/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
8827bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
8828 IdLocListType &IdLocList) {
8829 if (parseToken(lltok::lparen, "expected '(' here") ||
8830 parseParamNo(Param.ParamNo) ||
8831 parseToken(lltok::comma, "expected ',' here") ||
8832 parseParamAccessOffset(Param.Use))
8833 return true;
8834
8835 if (EatIfPresent(lltok::comma)) {
8836 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
8837 parseToken(lltok::colon, "expected ':' here") ||
8838 parseToken(lltok::lparen, "expected '(' here"))
8839 return true;
8840 do {
8841 FunctionSummary::ParamAccess::Call Call;
8842 if (parseParamAccessCall(Call, IdLocList))
8843 return true;
8844 Param.Calls.push_back(Call);
8845 } while (EatIfPresent(lltok::comma));
8846
8847 if (parseToken(lltok::rparen, "expected ')' here"))
8848 return true;
8849 }
8850
8851 if (parseToken(lltok::rparen, "expected ')' here"))
8852 return true;
8853
8854 return false;
8855}
8856
8857/// OptionalParamAccesses
8858/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
8859bool LLParser::parseOptionalParamAccesses(
8860 std::vector<FunctionSummary::ParamAccess> &Params) {
8861 assert(Lex.getKind() == lltok::kw_params)((void)0);
8862 Lex.Lex();
8863
8864 if (parseToken(lltok::colon, "expected ':' here") ||
8865 parseToken(lltok::lparen, "expected '(' here"))
8866 return true;
8867
8868 IdLocListType VContexts;
8869 size_t CallsNum = 0;
8870 do {
8871 FunctionSummary::ParamAccess ParamAccess;
8872 if (parseParamAccess(ParamAccess, VContexts))
8873 return true;
8874 CallsNum += ParamAccess.Calls.size();
8875 assert(VContexts.size() == CallsNum)((void)0);
8876 (void)CallsNum;
8877 Params.emplace_back(std::move(ParamAccess));
8878 } while (EatIfPresent(lltok::comma));
8879
8880 if (parseToken(lltok::rparen, "expected ')' here"))
8881 return true;
8882
8883 // Now that the Params is finalized, it is safe to save the locations
8884 // of any forward GV references that need updating later.
8885 IdLocListType::const_iterator ItContext = VContexts.begin();
8886 for (auto &PA : Params) {
8887 for (auto &C : PA.Calls) {
8888 if (C.Callee.getRef() == FwdVIRef)
8889 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
8890 ItContext->second);
8891 ++ItContext;
8892 }
8893 }
8894 assert(ItContext == VContexts.end())((void)0);
8895
8896 return false;
8897}
8898
8899/// OptionalRefs
8900/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
8901bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
8902 assert(Lex.getKind() == lltok::kw_refs)((void)0);
8903 Lex.Lex();
8904
8905 if (parseToken(lltok::colon, "expected ':' in refs") ||
8906 parseToken(lltok::lparen, "expected '(' in refs"))
8907 return true;
8908
8909 struct ValueContext {
8910 ValueInfo VI;
8911 unsigned GVId;
8912 LocTy Loc;
8913 };
8914 std::vector<ValueContext> VContexts;
8915 // parse each ref edge
8916 do {
8917 ValueContext VC;
8918 VC.Loc = Lex.getLoc();
8919 if (parseGVReference(VC.VI, VC.GVId))
8920 return true;
8921 VContexts.push_back(VC);
8922 } while (EatIfPresent(lltok::comma));
8923
8924 // Sort value contexts so that ones with writeonly
8925 // and readonly ValueInfo are at the end of VContexts vector.
8926 // See FunctionSummary::specialRefCounts()
8927 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
8928 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
8929 });
8930
8931 IdToIndexMapType IdToIndexMap;
8932 for (auto &VC : VContexts) {
8933 // Keep track of the Refs array index needing a forward reference.
8934 // We will save the location of the ValueInfo needing an update, but
8935 // can only do so once the std::vector is finalized.
8936 if (VC.VI.getRef() == FwdVIRef)
8937 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
8938 Refs.push_back(VC.VI);
8939 }
8940
8941 // Now that the Refs vector is finalized, it is safe to save the locations
8942 // of any forward GV references that need updating later.
8943 for (auto I : IdToIndexMap) {
8944 auto &Infos = ForwardRefValueInfos[I.first];
8945 for (auto P : I.second) {
8946 assert(Refs[P.first].getRef() == FwdVIRef &&((void)0)
8947 "Forward referenced ValueInfo expected to be empty")((void)0);
8948 Infos.emplace_back(&Refs[P.first], P.second);
8949 }
8950 }
8951
8952 if (parseToken(lltok::rparen, "expected ')' in refs"))
8953 return true;
8954
8955 return false;
8956}
8957
8958/// OptionalTypeIdInfo
8959/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8960/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8961/// [',' TypeCheckedLoadConstVCalls]? ')'
8962bool LLParser::parseOptionalTypeIdInfo(
8963 FunctionSummary::TypeIdInfo &TypeIdInfo) {
8964 assert(Lex.getKind() == lltok::kw_typeIdInfo)((void)0);
8965 Lex.Lex();
8966
8967 if (parseToken(lltok::colon, "expected ':' here") ||
8968 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8969 return true;
8970
8971 do {
8972 switch (Lex.getKind()) {
8973 case lltok::kw_typeTests:
8974 if (parseTypeTests(TypeIdInfo.TypeTests))
8975 return true;
8976 break;
8977 case lltok::kw_typeTestAssumeVCalls:
8978 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
8979 TypeIdInfo.TypeTestAssumeVCalls))
8980 return true;
8981 break;
8982 case lltok::kw_typeCheckedLoadVCalls:
8983 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
8984 TypeIdInfo.TypeCheckedLoadVCalls))
8985 return true;
8986 break;
8987 case lltok::kw_typeTestAssumeConstVCalls:
8988 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
8989 TypeIdInfo.TypeTestAssumeConstVCalls))
8990 return true;
8991 break;
8992 case lltok::kw_typeCheckedLoadConstVCalls:
8993 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
8994 TypeIdInfo.TypeCheckedLoadConstVCalls))
8995 return true;
8996 break;
8997 default:
8998 return error(Lex.getLoc(), "invalid typeIdInfo list type");
8999 }
9000 } while (EatIfPresent(lltok::comma));
9001
9002 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9003 return true;
9004
9005 return false;
9006}
9007
9008/// TypeTests
9009/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
9010/// [',' (SummaryID | UInt64)]* ')'
9011bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9012 assert(Lex.getKind() == lltok::kw_typeTests)((void)0);
9013 Lex.Lex();
9014
9015 if (parseToken(lltok::colon, "expected ':' here") ||
9016 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9017 return true;
9018
9019 IdToIndexMapType IdToIndexMap;
9020 do {
9021 GlobalValue::GUID GUID = 0;
9022 if (Lex.getKind() == lltok::SummaryID) {
9023 unsigned ID = Lex.getUIntVal();
9024 LocTy Loc = Lex.getLoc();
9025 // Keep track of the TypeTests array index needing a forward reference.
9026 // We will save the location of the GUID needing an update, but
9027 // can only do so once the std::vector is finalized.
9028 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
9029 Lex.Lex();
9030 } else if (parseUInt64(GUID))
9031 return true;
9032 TypeTests.push_back(GUID);
9033 } while (EatIfPresent(lltok::comma));
9034
9035 // Now that the TypeTests vector is finalized, it is safe to save the
9036 // locations of any forward GV references that need updating later.
9037 for (auto I : IdToIndexMap) {
9038 auto &Ids = ForwardRefTypeIds[I.first];
9039 for (auto P : I.second) {
9040 assert(TypeTests[P.first] == 0 &&((void)0)
9041 "Forward referenced type id GUID expected to be 0")((void)0);
9042 Ids.emplace_back(&TypeTests[P.first], P.second);
9043 }
9044 }
9045
9046 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9047 return true;
9048
9049 return false;
9050}
9051
9052/// VFuncIdList
9053/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
9054bool LLParser::parseVFuncIdList(
9055 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
9056 assert(Lex.getKind() == Kind)((void)0);
9057 Lex.Lex();
9058
9059 if (parseToken(lltok::colon, "expected ':' here") ||
9060 parseToken(lltok::lparen, "expected '(' here"))
9061 return true;
9062
9063 IdToIndexMapType IdToIndexMap;
9064 do {
9065 FunctionSummary::VFuncId VFuncId;
9066 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
9067 return true;
9068 VFuncIdList.push_back(VFuncId);
9069 } while (EatIfPresent(lltok::comma));
9070
9071 if (parseToken(lltok::rparen, "expected ')' here"))
9072 return true;
9073
9074 // Now that the VFuncIdList vector is finalized, it is safe to save the
9075 // locations of any forward GV references that need updating later.
9076 for (auto I : IdToIndexMap) {
9077 auto &Ids = ForwardRefTypeIds[I.first];
9078 for (auto P : I.second) {
9079 assert(VFuncIdList[P.first].GUID == 0 &&((void)0)
9080 "Forward referenced type id GUID expected to be 0")((void)0);
9081 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
9082 }
9083 }
9084
9085 return false;
9086}
9087
9088/// ConstVCallList
9089/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
9090bool LLParser::parseConstVCallList(
9091 lltok::Kind Kind,
9092 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
9093 assert(Lex.getKind() == Kind)((void)0);
9094 Lex.Lex();
9095
9096 if (parseToken(lltok::colon, "expected ':' here") ||
9097 parseToken(lltok::lparen, "expected '(' here"))
9098 return true;
9099
9100 IdToIndexMapType IdToIndexMap;
9101 do {
9102 FunctionSummary::ConstVCall ConstVCall;
9103 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
9104 return true;
9105 ConstVCallList.push_back(ConstVCall);
9106 } while (EatIfPresent(lltok::comma));
9107
9108 if (parseToken(lltok::rparen, "expected ')' here"))
9109 return true;
9110
9111 // Now that the ConstVCallList vector is finalized, it is safe to save the
9112 // locations of any forward GV references that need updating later.
9113 for (auto I : IdToIndexMap) {
9114 auto &Ids = ForwardRefTypeIds[I.first];
9115 for (auto P : I.second) {
9116 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&((void)0)
9117 "Forward referenced type id GUID expected to be 0")((void)0);
9118 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
9119 }
9120 }
9121
9122 return false;
9123}
9124
9125/// ConstVCall
9126/// ::= '(' VFuncId ',' Args ')'
9127bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
9128 IdToIndexMapType &IdToIndexMap, unsigned Index) {
9129 if (parseToken(lltok::lparen, "expected '(' here") ||
9130 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
9131 return true;
9132
9133 if (EatIfPresent(lltok::comma))
9134 if (parseArgs(ConstVCall.Args))
9135 return true;
9136
9137 if (parseToken(lltok::rparen, "expected ')' here"))
9138 return true;
9139
9140 return false;
9141}
9142
9143/// VFuncId
9144/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
9145/// 'offset' ':' UInt64 ')'
9146bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
9147 IdToIndexMapType &IdToIndexMap, unsigned Index) {
9148 assert(Lex.getKind() == lltok::kw_vFuncId)((void)0);
9149 Lex.Lex();
9150
9151 if (parseToken(lltok::colon, "expected ':' here") ||
9152 parseToken(lltok::lparen, "expected '(' here"))
9153 return true;
9154
9155 if (Lex.getKind() == lltok::SummaryID) {
9156 VFuncId.GUID = 0;
9157 unsigned ID = Lex.getUIntVal();
9158 LocTy Loc = Lex.getLoc();
9159 // Keep track of the array index needing a forward reference.
9160 // We will save the location of the GUID needing an update, but
9161 // can only do so once the caller's std::vector is finalized.
9162 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
9163 Lex.Lex();
9164 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
9165 parseToken(lltok::colon, "expected ':' here") ||
9166 parseUInt64(VFuncId.GUID))
9167 return true;
9168
9169 if (parseToken(lltok::comma, "expected ',' here") ||
9170 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9171 parseToken(lltok::colon, "expected ':' here") ||
9172 parseUInt64(VFuncId.Offset) ||
9173 parseToken(lltok::rparen, "expected ')' here"))
9174 return true;
9175
9176 return false;
9177}
9178
9179/// GVFlags
9180/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
9181/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
9182/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
9183/// 'canAutoHide' ':' Flag ',' ')'
9184bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
9185 assert(Lex.getKind() == lltok::kw_flags)((void)0);
9186 Lex.Lex();
9187
9188 if (parseToken(lltok::colon, "expected ':' here") ||
9189 parseToken(lltok::lparen, "expected '(' here"))
9190 return true;
9191
9192 do {
9193 unsigned Flag = 0;
9194 switch (Lex.getKind()) {
9195 case lltok::kw_linkage:
9196 Lex.Lex();
9197 if (parseToken(lltok::colon, "expected ':'"))
9198 return true;
9199 bool HasLinkage;
9200 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
9201 assert(HasLinkage && "Linkage not optional in summary entry")((void)0);
9202 Lex.Lex();
9203 break;
9204 case lltok::kw_visibility:
9205 Lex.Lex();
9206 if (parseToken(lltok::colon, "expected ':'"))
9207 return true;
9208 parseOptionalVisibility(Flag);
9209 GVFlags.Visibility = Flag;
9210 break;
9211 case lltok::kw_notEligibleToImport:
9212 Lex.Lex();
9213 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9214 return true;
9215 GVFlags.NotEligibleToImport = Flag;
9216 break;
9217 case lltok::kw_live:
9218 Lex.Lex();
9219 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9220 return true;
9221 GVFlags.Live = Flag;
9222 break;
9223 case lltok::kw_dsoLocal:
9224 Lex.Lex();
9225 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9226 return true;
9227 GVFlags.DSOLocal = Flag;
9228 break;
9229 case lltok::kw_canAutoHide:
9230 Lex.Lex();
9231 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9232 return true;
9233 GVFlags.CanAutoHide = Flag;
9234 break;
9235 default:
9236 return error(Lex.getLoc(), "expected gv flag type");
9237 }
9238 } while (EatIfPresent(lltok::comma));
9239
9240 if (parseToken(lltok::rparen, "expected ')' here"))
9241 return true;
9242
9243 return false;
9244}
9245
9246/// GVarFlags
9247/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
9248/// ',' 'writeonly' ':' Flag
9249/// ',' 'constant' ':' Flag ')'
9250bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
9251 assert(Lex.getKind() == lltok::kw_varFlags)((void)0);
9252 Lex.Lex();
9253
9254 if (parseToken(lltok::colon, "expected ':' here") ||
9255 parseToken(lltok::lparen, "expected '(' here"))
9256 return true;
9257
9258 auto ParseRest = [this](unsigned int &Val) {
9259 Lex.Lex();
9260 if (parseToken(lltok::colon, "expected ':'"))
9261 return true;
9262 return parseFlag(Val);
9263 };
9264
9265 do {
9266 unsigned Flag = 0;
9267 switch (Lex.getKind()) {
9268 case lltok::kw_readonly:
9269 if (ParseRest(Flag))
9270 return true;
9271 GVarFlags.MaybeReadOnly = Flag;
9272 break;
9273 case lltok::kw_writeonly:
9274 if (ParseRest(Flag))
9275 return true;
9276 GVarFlags.MaybeWriteOnly = Flag;
9277 break;
9278 case lltok::kw_constant:
9279 if (ParseRest(Flag))
9280 return true;
9281 GVarFlags.Constant = Flag;
9282 break;
9283 case lltok::kw_vcall_visibility:
9284 if (ParseRest(Flag))
9285 return true;
9286 GVarFlags.VCallVisibility = Flag;
9287 break;
9288 default:
9289 return error(Lex.getLoc(), "expected gvar flag type");
9290 }
9291 } while (EatIfPresent(lltok::comma));
9292 return parseToken(lltok::rparen, "expected ')' here");
9293}
9294
9295/// ModuleReference
9296/// ::= 'module' ':' UInt
9297bool LLParser::parseModuleReference(StringRef &ModulePath) {
9298 // parse module id.
9299 if (parseToken(lltok::kw_module, "expected 'module' here") ||
9300 parseToken(lltok::colon, "expected ':' here") ||
9301 parseToken(lltok::SummaryID, "expected module ID"))
9302 return true;
9303
9304 unsigned ModuleID = Lex.getUIntVal();
9305 auto I = ModuleIdMap.find(ModuleID);
9306 // We should have already parsed all module IDs
9307 assert(I != ModuleIdMap.end())((void)0);
9308 ModulePath = I->second;
9309 return false;
9310}
9311
9312/// GVReference
9313/// ::= SummaryID
9314bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
9315 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
9316 if (!ReadOnly)
9317 WriteOnly = EatIfPresent(lltok::kw_writeonly);
9318 if (parseToken(lltok::SummaryID, "expected GV ID"))
9319 return true;
9320
9321 GVId = Lex.getUIntVal();
9322 // Check if we already have a VI for this GV
9323 if (GVId < NumberedValueInfos.size()) {
9324 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef)((void)0);
9325 VI = NumberedValueInfos[GVId];
9326 } else
9327 // We will create a forward reference to the stored location.
9328 VI = ValueInfo(false, FwdVIRef);
9329
9330 if (ReadOnly)
9331 VI.setReadOnly();
9332 if (WriteOnly)
9333 VI.setWriteOnly();
9334 return false;
9335}