Bug Summary

File:lib/AsmParser/LLParser.h
Warning:line 178, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Parser.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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/lib/AsmParser -I /build/llvm-toolchain-snapshot-8~svn350071/lib/AsmParser -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn350071/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/lib/AsmParser -fdebug-prefix-map=/build/llvm-toolchain-snapshot-8~svn350071=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-12-27-042839-1215-1 -x c++ /build/llvm-toolchain-snapshot-8~svn350071/lib/AsmParser/Parser.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn350071/lib/AsmParser/Parser.cpp

1//===- Parser.cpp - Main dispatch module for the Parser library -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This library implements the functionality defined in llvm/AsmParser/Parser.h
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/AsmParser/Parser.h"
15#include "LLParser.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/IR/Module.h"
18#include "llvm/IR/ModuleSummaryIndex.h"
19#include "llvm/Support/MemoryBuffer.h"
20#include "llvm/Support/SourceMgr.h"
21#include "llvm/Support/raw_ostream.h"
22#include <cstring>
23#include <system_error>
24using namespace llvm;
25
26bool llvm::parseAssemblyInto(MemoryBufferRef F, Module *M,
27 ModuleSummaryIndex *Index, SMDiagnostic &Err,
28 SlotMapping *Slots, bool UpgradeDebugInfo,
29 StringRef DataLayoutString) {
30 SourceMgr SM;
31 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(F);
32 SM.AddNewSourceBuffer(std::move(Buf), SMLoc());
33
34 LLVMContext Context;
35 return LLParser(F.getBuffer(), SM, Err, M, Index,
36 M ? M->getContext() : Context, Slots, UpgradeDebugInfo,
37 DataLayoutString)
38 .Run();
39}
40
41std::unique_ptr<Module>
42llvm::parseAssembly(MemoryBufferRef F, SMDiagnostic &Err, LLVMContext &Context,
43 SlotMapping *Slots, bool UpgradeDebugInfo,
44 StringRef DataLayoutString) {
45 std::unique_ptr<Module> M =
46 make_unique<Module>(F.getBufferIdentifier(), Context);
47
48 if (parseAssemblyInto(F, M.get(), nullptr, Err, Slots, UpgradeDebugInfo,
49 DataLayoutString))
50 return nullptr;
51
52 return M;
53}
54
55std::unique_ptr<Module>
56llvm::parseAssemblyFile(StringRef Filename, SMDiagnostic &Err,
57 LLVMContext &Context, SlotMapping *Slots,
58 bool UpgradeDebugInfo, StringRef DataLayoutString) {
59 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
60 MemoryBuffer::getFileOrSTDIN(Filename);
61 if (std::error_code EC = FileOrErr.getError()) {
62 Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
63 "Could not open input file: " + EC.message());
64 return nullptr;
65 }
66
67 return parseAssembly(FileOrErr.get()->getMemBufferRef(), Err, Context, Slots,
68 UpgradeDebugInfo, DataLayoutString);
69}
70
71ParsedModuleAndIndex llvm::parseAssemblyWithIndex(
72 MemoryBufferRef F, SMDiagnostic &Err, LLVMContext &Context,
73 SlotMapping *Slots, bool UpgradeDebugInfo, StringRef DataLayoutString) {
74 std::unique_ptr<Module> M =
75 make_unique<Module>(F.getBufferIdentifier(), Context);
76 std::unique_ptr<ModuleSummaryIndex> Index =
77 make_unique<ModuleSummaryIndex>(/*HaveGVs=*/true);
78
79 if (parseAssemblyInto(F, M.get(), Index.get(), Err, Slots, UpgradeDebugInfo,
80 DataLayoutString))
81 return {nullptr, nullptr};
82
83 return {std::move(M), std::move(Index)};
84}
85
86ParsedModuleAndIndex llvm::parseAssemblyFileWithIndex(
87 StringRef Filename, SMDiagnostic &Err, LLVMContext &Context,
88 SlotMapping *Slots, bool UpgradeDebugInfo, StringRef DataLayoutString) {
89 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
90 MemoryBuffer::getFileOrSTDIN(Filename);
91 if (std::error_code EC = FileOrErr.getError()) {
92 Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
93 "Could not open input file: " + EC.message());
94 return {nullptr, nullptr};
95 }
96
97 return parseAssemblyWithIndex(FileOrErr.get()->getMemBufferRef(), Err,
98 Context, Slots, UpgradeDebugInfo,
99 DataLayoutString);
100}
101
102std::unique_ptr<Module>
103llvm::parseAssemblyString(StringRef AsmString, SMDiagnostic &Err,
104 LLVMContext &Context, SlotMapping *Slots,
105 bool UpgradeDebugInfo, StringRef DataLayoutString) {
106 MemoryBufferRef F(AsmString, "<string>");
107 return parseAssembly(F, Err, Context, Slots, UpgradeDebugInfo,
108 DataLayoutString);
109}
110
111static bool parseSummaryIndexAssemblyInto(MemoryBufferRef F,
112 ModuleSummaryIndex &Index,
113 SMDiagnostic &Err) {
114 SourceMgr SM;
115 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(F);
116 SM.AddNewSourceBuffer(std::move(Buf), SMLoc());
117
118 // The parser holds a reference to a context that is unused when parsing the
119 // index, but we need to initialize it.
120 LLVMContext unusedContext;
121 return LLParser(F.getBuffer(), SM, Err, nullptr, &Index, unusedContext).Run();
4
Passing null pointer value via 4th parameter 'M'
5
Calling constructor for 'LLParser'
122}
123
124std::unique_ptr<ModuleSummaryIndex>
125llvm::parseSummaryIndexAssembly(MemoryBufferRef F, SMDiagnostic &Err) {
126 std::unique_ptr<ModuleSummaryIndex> Index =
127 make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
128
129 if (parseSummaryIndexAssemblyInto(F, *Index, Err))
3
Calling 'parseSummaryIndexAssemblyInto'
130 return nullptr;
131
132 return Index;
133}
134
135std::unique_ptr<ModuleSummaryIndex>
136llvm::parseSummaryIndexAssemblyFile(StringRef Filename, SMDiagnostic &Err) {
137 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
138 MemoryBuffer::getFileOrSTDIN(Filename);
139 if (std::error_code EC = FileOrErr.getError()) {
1
Taking false branch
140 Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
141 "Could not open input file: " + EC.message());
142 return nullptr;
143 }
144
145 return parseSummaryIndexAssembly(FileOrErr.get()->getMemBufferRef(), Err);
2
Calling 'parseSummaryIndexAssembly'
146}
147
148Constant *llvm::parseConstantValue(StringRef Asm, SMDiagnostic &Err,
149 const Module &M, const SlotMapping *Slots) {
150 SourceMgr SM;
151 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Asm);
152 SM.AddNewSourceBuffer(std::move(Buf), SMLoc());
153 Constant *C;
154 if (LLParser(Asm, SM, Err, const_cast<Module *>(&M), nullptr, M.getContext())
155 .parseStandaloneConstantValue(C, Slots))
156 return nullptr;
157 return C;
158}
159
160Type *llvm::parseType(StringRef Asm, SMDiagnostic &Err, const Module &M,
161 const SlotMapping *Slots) {
162 unsigned Read;
163 Type *Ty = parseTypeAtBeginning(Asm, Read, Err, M, Slots);
164 if (!Ty)
165 return nullptr;
166 if (Read != Asm.size()) {
167 SourceMgr SM;
168 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Asm);
169 SM.AddNewSourceBuffer(std::move(Buf), SMLoc());
170 Err = SM.GetMessage(SMLoc::getFromPointer(Asm.begin() + Read),
171 SourceMgr::DK_Error, "expected end of string");
172 return nullptr;
173 }
174 return Ty;
175}
176Type *llvm::parseTypeAtBeginning(StringRef Asm, unsigned &Read,
177 SMDiagnostic &Err, const Module &M,
178 const SlotMapping *Slots) {
179 SourceMgr SM;
180 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Asm);
181 SM.AddNewSourceBuffer(std::move(Buf), SMLoc());
182 Type *Ty;
183 if (LLParser(Asm, SM, Err, const_cast<Module *>(&M), nullptr, M.getContext())
184 .parseTypeAtBeginning(Ty, Read, Slots))
185 return nullptr;
186 return Ty;
187}

/build/llvm-toolchain-snapshot-8~svn350071/lib/AsmParser/LLParser.h

1//===-- LLParser.h - Parser Class -------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_LIB_ASMPARSER_LLPARSER_H
15#define LLVM_LIB_ASMPARSER_LLPARSER_H
16
17#include "LLLexer.h"
18#include "llvm/ADT/Optional.h"
19#include "llvm/ADT/StringMap.h"
20#include "llvm/IR/Attributes.h"
21#include "llvm/IR/Instructions.h"
22#include "llvm/IR/Module.h"
23#include "llvm/IR/ModuleSummaryIndex.h"
24#include "llvm/IR/Operator.h"
25#include "llvm/IR/Type.h"
26#include "llvm/IR/ValueHandle.h"
27#include <map>
28
29namespace llvm {
30 class Module;
31 class OpaqueType;
32 class Function;
33 class Value;
34 class BasicBlock;
35 class Instruction;
36 class Constant;
37 class GlobalValue;
38 class Comdat;
39 class MDString;
40 class MDNode;
41 struct SlotMapping;
42 class StructType;
43
44 /// ValID - Represents a reference of a definition of some sort with no type.
45 /// There are several cases where we have to parse the value but where the
46 /// type can depend on later context. This may either be a numeric reference
47 /// or a symbolic (%var) reference. This is just a discriminated union.
48 struct ValID {
49 enum {
50 t_LocalID, t_GlobalID, // ID in UIntVal.
51 t_LocalName, t_GlobalName, // Name in StrVal.
52 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
53 t_Null, t_Undef, t_Zero, t_None, // No value.
54 t_EmptyArray, // No value: []
55 t_Constant, // Value in ConstantVal.
56 t_InlineAsm, // Value in FTy/StrVal/StrVal2/UIntVal.
57 t_ConstantStruct, // Value in ConstantStructElts.
58 t_PackedConstantStruct // Value in ConstantStructElts.
59 } Kind = t_LocalID;
60
61 LLLexer::LocTy Loc;
62 unsigned UIntVal;
63 FunctionType *FTy = nullptr;
64 std::string StrVal, StrVal2;
65 APSInt APSIntVal;
66 APFloat APFloatVal{0.0};
67 Constant *ConstantVal;
68 std::unique_ptr<Constant *[]> ConstantStructElts;
69
70 ValID() = default;
71 ValID(const ValID &RHS)
72 : Kind(RHS.Kind), Loc(RHS.Loc), UIntVal(RHS.UIntVal), FTy(RHS.FTy),
73 StrVal(RHS.StrVal), StrVal2(RHS.StrVal2), APSIntVal(RHS.APSIntVal),
74 APFloatVal(RHS.APFloatVal), ConstantVal(RHS.ConstantVal) {
75 assert(!RHS.ConstantStructElts)((!RHS.ConstantStructElts) ? static_cast<void> (0) : __assert_fail
("!RHS.ConstantStructElts", "/build/llvm-toolchain-snapshot-8~svn350071/lib/AsmParser/LLParser.h"
, 75, __PRETTY_FUNCTION__))
;
76 }
77
78 bool operator<(const ValID &RHS) const {
79 if (Kind == t_LocalID || Kind == t_GlobalID)
80 return UIntVal < RHS.UIntVal;
81 assert((Kind == t_LocalName || Kind == t_GlobalName ||(((Kind == t_LocalName || Kind == t_GlobalName || Kind == t_ConstantStruct
|| Kind == t_PackedConstantStruct) && "Ordering not defined for this ValID kind yet"
) ? static_cast<void> (0) : __assert_fail ("(Kind == t_LocalName || Kind == t_GlobalName || Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) && \"Ordering not defined for this ValID kind yet\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/AsmParser/LLParser.h"
, 83, __PRETTY_FUNCTION__))
82 Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&(((Kind == t_LocalName || Kind == t_GlobalName || Kind == t_ConstantStruct
|| Kind == t_PackedConstantStruct) && "Ordering not defined for this ValID kind yet"
) ? static_cast<void> (0) : __assert_fail ("(Kind == t_LocalName || Kind == t_GlobalName || Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) && \"Ordering not defined for this ValID kind yet\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/AsmParser/LLParser.h"
, 83, __PRETTY_FUNCTION__))
83 "Ordering not defined for this ValID kind yet")(((Kind == t_LocalName || Kind == t_GlobalName || Kind == t_ConstantStruct
|| Kind == t_PackedConstantStruct) && "Ordering not defined for this ValID kind yet"
) ? static_cast<void> (0) : __assert_fail ("(Kind == t_LocalName || Kind == t_GlobalName || Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) && \"Ordering not defined for this ValID kind yet\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/AsmParser/LLParser.h"
, 83, __PRETTY_FUNCTION__))
;
84 return StrVal < RHS.StrVal;
85 }
86 };
87
88 class LLParser {
89 public:
90 typedef LLLexer::LocTy LocTy;
91 private:
92 LLVMContext &Context;
93 LLLexer Lex;
94 // Module being parsed, null if we are only parsing summary index.
95 Module *M;
96 // Summary index being parsed, null if we are only parsing Module.
97 ModuleSummaryIndex *Index;
98 SlotMapping *Slots;
99
100 // Instruction metadata resolution. Each instruction can have a list of
101 // MDRef info associated with them.
102 //
103 // The simpler approach of just creating temporary MDNodes and then calling
104 // RAUW on them when the definition is processed doesn't work because some
105 // instruction metadata kinds, such as dbg, get stored in the IR in an
106 // "optimized" format which doesn't participate in the normal value use
107 // lists. This means that RAUW doesn't work, even on temporary MDNodes
108 // which otherwise support RAUW. Instead, we defer resolving MDNode
109 // references until the definitions have been processed.
110 struct MDRef {
111 SMLoc Loc;
112 unsigned MDKind, MDSlot;
113 };
114
115 SmallVector<Instruction*, 64> InstsWithTBAATag;
116
117 // Type resolution handling data structures. The location is set when we
118 // have processed a use of the type but not a definition yet.
119 StringMap<std::pair<Type*, LocTy> > NamedTypes;
120 std::map<unsigned, std::pair<Type*, LocTy> > NumberedTypes;
121
122 std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
123 std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
124
125 // Global Value reference information.
126 std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
127 std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
128 std::vector<GlobalValue*> NumberedVals;
129
130 // Comdat forward reference information.
131 std::map<std::string, LocTy> ForwardRefComdats;
132
133 // References to blockaddress. The key is the function ValID, the value is
134 // a list of references to blocks in that function.
135 std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
136 class PerFunctionState;
137 /// Reference to per-function state to allow basic blocks to be
138 /// forward-referenced by blockaddress instructions within the same
139 /// function.
140 PerFunctionState *BlockAddressPFS;
141
142 // Attribute builder reference information.
143 std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
144 std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
145
146 // Summary global value reference information.
147 std::map<unsigned, std::vector<std::pair<ValueInfo *, LocTy>>>
148 ForwardRefValueInfos;
149 std::map<unsigned, std::vector<std::pair<AliasSummary *, LocTy>>>
150 ForwardRefAliasees;
151 std::vector<ValueInfo> NumberedValueInfos;
152
153 // Summary type id reference information.
154 std::map<unsigned, std::vector<std::pair<GlobalValue::GUID *, LocTy>>>
155 ForwardRefTypeIds;
156
157 // Map of module ID to path.
158 std::map<unsigned, StringRef> ModuleIdMap;
159
160 /// Only the llvm-as tool may set this to false to bypass
161 /// UpgradeDebuginfo so it can generate broken bitcode.
162 bool UpgradeDebugInfo;
163
164 /// DataLayout string to override that in LLVM assembly.
165 StringRef DataLayoutStr;
166
167 std::string SourceFileName;
168
169 public:
170 LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *M,
171 ModuleSummaryIndex *Index, LLVMContext &Context,
172 SlotMapping *Slots = nullptr, bool UpgradeDebugInfo = true,
173 StringRef DataLayoutString = "")
174 : Context(Context), Lex(F, SM, Err, Context), M(M), Index(Index),
175 Slots(Slots), BlockAddressPFS(nullptr),
176 UpgradeDebugInfo(UpgradeDebugInfo), DataLayoutStr(DataLayoutString) {
177 if (!DataLayoutStr.empty())
6
Assuming the condition is true
7
Taking true branch
178 M->setDataLayout(DataLayoutStr);
8
Called C++ object pointer is null
179 }
180 bool Run();
181
182 bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots);
183
184 bool parseTypeAtBeginning(Type *&Ty, unsigned &Read,
185 const SlotMapping *Slots);
186
187 LLVMContext &getContext() { return Context; }
188
189 private:
190
191 bool Error(LocTy L, const Twine &Msg) const {
192 return Lex.Error(L, Msg);
193 }
194 bool TokError(const Twine &Msg) const {
195 return Error(Lex.getLoc(), Msg);
196 }
197
198 /// Restore the internal name and slot mappings using the mappings that
199 /// were created at an earlier parsing stage.
200 void restoreParsingState(const SlotMapping *Slots);
201
202 /// GetGlobalVal - Get a value with the specified name or ID, creating a
203 /// forward reference record if needed. This can return null if the value
204 /// exists but does not have the right type.
205 GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc,
206 bool IsCall);
207 GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc, bool IsCall);
208
209 /// Get a Comdat with the specified name, creating a forward reference
210 /// record if needed.
211 Comdat *getComdat(const std::string &Name, LocTy Loc);
212
213 // Helper Routines.
214 bool ParseToken(lltok::Kind T, const char *ErrMsg);
215 bool EatIfPresent(lltok::Kind T) {
216 if (Lex.getKind() != T) return false;
217 Lex.Lex();
218 return true;
219 }
220
221 FastMathFlags EatFastMathFlagsIfPresent() {
222 FastMathFlags FMF;
223 while (true)
224 switch (Lex.getKind()) {
225 case lltok::kw_fast: FMF.setFast(); Lex.Lex(); continue;
226 case lltok::kw_nnan: FMF.setNoNaNs(); Lex.Lex(); continue;
227 case lltok::kw_ninf: FMF.setNoInfs(); Lex.Lex(); continue;
228 case lltok::kw_nsz: FMF.setNoSignedZeros(); Lex.Lex(); continue;
229 case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
230 case lltok::kw_contract:
231 FMF.setAllowContract(true);
232 Lex.Lex();
233 continue;
234 case lltok::kw_reassoc: FMF.setAllowReassoc(); Lex.Lex(); continue;
235 case lltok::kw_afn: FMF.setApproxFunc(); Lex.Lex(); continue;
236 default: return FMF;
237 }
238 return FMF;
239 }
240
241 bool ParseOptionalToken(lltok::Kind T, bool &Present,
242 LocTy *Loc = nullptr) {
243 if (Lex.getKind() != T) {
244 Present = false;
245 } else {
246 if (Loc)
247 *Loc = Lex.getLoc();
248 Lex.Lex();
249 Present = true;
250 }
251 return false;
252 }
253 bool ParseStringConstant(std::string &Result);
254 bool ParseUInt32(unsigned &Val);
255 bool ParseUInt32(unsigned &Val, LocTy &Loc) {
256 Loc = Lex.getLoc();
257 return ParseUInt32(Val);
258 }
259 bool ParseUInt64(uint64_t &Val);
260 bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
261 Loc = Lex.getLoc();
262 return ParseUInt64(Val);
263 }
264 bool ParseFlag(unsigned &Val);
265
266 bool ParseStringAttribute(AttrBuilder &B);
267
268 bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
269 bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
270 bool ParseOptionalUnnamedAddr(GlobalVariable::UnnamedAddr &UnnamedAddr);
271 bool ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS = 0);
272 bool ParseOptionalProgramAddrSpace(unsigned &AddrSpace) {
273 return ParseOptionalAddrSpace(
274 AddrSpace, M->getDataLayout().getProgramAddressSpace());
275 };
276 bool ParseOptionalParamAttrs(AttrBuilder &B);
277 bool ParseOptionalReturnAttrs(AttrBuilder &B);
278 bool ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
279 unsigned &Visibility, unsigned &DLLStorageClass,
280 bool &DSOLocal);
281 void ParseOptionalDSOLocal(bool &DSOLocal);
282 void ParseOptionalVisibility(unsigned &Res);
283 void ParseOptionalDLLStorageClass(unsigned &Res);
284 bool ParseOptionalCallingConv(unsigned &CC);
285 bool ParseOptionalAlignment(unsigned &Alignment);
286 bool ParseOptionalDerefAttrBytes(lltok::Kind AttrKind, uint64_t &Bytes);
287 bool ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
288 AtomicOrdering &Ordering);
289 bool ParseScope(SyncScope::ID &SSID);
290 bool ParseOrdering(AtomicOrdering &Ordering);
291 bool ParseOptionalStackAlignment(unsigned &Alignment);
292 bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
293 bool ParseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
294 bool &AteExtraComma);
295 bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
296 bool parseAllocSizeArguments(unsigned &BaseSizeArg,
297 Optional<unsigned> &HowManyArg);
298 bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,
299 bool &AteExtraComma);
300 bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
301 bool AteExtraComma;
302 if (ParseIndexList(Indices, AteExtraComma)) return true;
303 if (AteExtraComma)
304 return TokError("expected index");
305 return false;
306 }
307
308 // Top-Level Entities
309 bool ParseTopLevelEntities();
310 bool ValidateEndOfModule();
311 bool ValidateEndOfIndex();
312 bool ParseTargetDefinition();
313 bool ParseModuleAsm();
314 bool ParseSourceFileName();
315 bool ParseDepLibs(); // FIXME: Remove in 4.0.
316 bool ParseUnnamedType();
317 bool ParseNamedType();
318 bool ParseDeclare();
319 bool ParseDefine();
320
321 bool ParseGlobalType(bool &IsConstant);
322 bool ParseUnnamedGlobal();
323 bool ParseNamedGlobal();
324 bool ParseGlobal(const std::string &Name, LocTy NameLoc, unsigned Linkage,
325 bool HasLinkage, unsigned Visibility,
326 unsigned DLLStorageClass, bool DSOLocal,
327 GlobalVariable::ThreadLocalMode TLM,
328 GlobalVariable::UnnamedAddr UnnamedAddr);
329 bool parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
330 unsigned L, unsigned Visibility,
331 unsigned DLLStorageClass, bool DSOLocal,
332 GlobalVariable::ThreadLocalMode TLM,
333 GlobalVariable::UnnamedAddr UnnamedAddr);
334 bool parseComdat();
335 bool ParseStandaloneMetadata();
336 bool ParseNamedMetadata();
337 bool ParseMDString(MDString *&Result);
338 bool ParseMDNodeID(MDNode *&Result);
339 bool ParseUnnamedAttrGrp();
340 bool ParseFnAttributeValuePairs(AttrBuilder &B,
341 std::vector<unsigned> &FwdRefAttrGrps,
342 bool inAttrGrp, LocTy &BuiltinLoc);
343
344 // Module Summary Index Parsing.
345 bool SkipModuleSummaryEntry();
346 bool ParseSummaryEntry();
347 bool ParseModuleEntry(unsigned ID);
348 bool ParseModuleReference(StringRef &ModulePath);
349 bool ParseGVReference(ValueInfo &VI, unsigned &GVId);
350 bool ParseGVEntry(unsigned ID);
351 bool ParseFunctionSummary(std::string Name, GlobalValue::GUID, unsigned ID);
352 bool ParseVariableSummary(std::string Name, GlobalValue::GUID, unsigned ID);
353 bool ParseAliasSummary(std::string Name, GlobalValue::GUID, unsigned ID);
354 bool ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags);
355 bool ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags);
356 bool ParseOptionalFFlags(FunctionSummary::FFlags &FFlags);
357 bool ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls);
358 bool ParseHotness(CalleeInfo::HotnessType &Hotness);
359 bool ParseOptionalTypeIdInfo(FunctionSummary::TypeIdInfo &TypeIdInfo);
360 bool ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests);
361 bool ParseVFuncIdList(lltok::Kind Kind,
362 std::vector<FunctionSummary::VFuncId> &VFuncIdList);
363 bool ParseConstVCallList(
364 lltok::Kind Kind,
365 std::vector<FunctionSummary::ConstVCall> &ConstVCallList);
366 using IdToIndexMapType =
367 std::map<unsigned, std::vector<std::pair<unsigned, LocTy>>>;
368 bool ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
369 IdToIndexMapType &IdToIndexMap, unsigned Index);
370 bool ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
371 IdToIndexMapType &IdToIndexMap, unsigned Index);
372 bool ParseOptionalRefs(std::vector<ValueInfo> &Refs);
373 bool ParseTypeIdEntry(unsigned ID);
374 bool ParseTypeIdSummary(TypeIdSummary &TIS);
375 bool ParseTypeTestResolution(TypeTestResolution &TTRes);
376 bool ParseOptionalWpdResolutions(
377 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap);
378 bool ParseWpdRes(WholeProgramDevirtResolution &WPDRes);
379 bool ParseOptionalResByArg(
380 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
381 &ResByArg);
382 bool ParseArgs(std::vector<uint64_t> &Args);
383 void AddGlobalValueToIndex(std::string Name, GlobalValue::GUID,
384 GlobalValue::LinkageTypes Linkage, unsigned ID,
385 std::unique_ptr<GlobalValueSummary> Summary);
386
387 // Type Parsing.
388 bool ParseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
389 bool ParseType(Type *&Result, bool AllowVoid = false) {
390 return ParseType(Result, "expected type", AllowVoid);
391 }
392 bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
393 bool AllowVoid = false) {
394 Loc = Lex.getLoc();
395 return ParseType(Result, Msg, AllowVoid);
396 }
397 bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
398 Loc = Lex.getLoc();
399 return ParseType(Result, AllowVoid);
400 }
401 bool ParseAnonStructType(Type *&Result, bool Packed);
402 bool ParseStructBody(SmallVectorImpl<Type*> &Body);
403 bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
404 std::pair<Type*, LocTy> &Entry,
405 Type *&ResultTy);
406
407 bool ParseArrayVectorType(Type *&Result, bool isVector);
408 bool ParseFunctionType(Type *&Result);
409
410 // Function Semantic Analysis.
411 class PerFunctionState {
412 LLParser &P;
413 Function &F;
414 std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
415 std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
416 std::vector<Value*> NumberedVals;
417
418 /// FunctionNumber - If this is an unnamed function, this is the slot
419 /// number of it, otherwise it is -1.
420 int FunctionNumber;
421 public:
422 PerFunctionState(LLParser &p, Function &f, int functionNumber);
423 ~PerFunctionState();
424
425 Function &getFunction() const { return F; }
426
427 bool FinishFunction();
428
429 /// GetVal - Get a value with the specified name or ID, creating a
430 /// forward reference record if needed. This can return null if the value
431 /// exists but does not have the right type.
432 Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc, bool IsCall);
433 Value *GetVal(unsigned ID, Type *Ty, LocTy Loc, bool IsCall);
434
435 /// SetInstName - After an instruction is parsed and inserted into its
436 /// basic block, this installs its name.
437 bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
438 Instruction *Inst);
439
440 /// GetBB - Get a basic block with the specified name or ID, creating a
441 /// forward reference record if needed. This can return null if the value
442 /// is not a BasicBlock.
443 BasicBlock *GetBB(const std::string &Name, LocTy Loc);
444 BasicBlock *GetBB(unsigned ID, LocTy Loc);
445
446 /// DefineBB - Define the specified basic block, which is either named or
447 /// unnamed. If there is an error, this returns null otherwise it returns
448 /// the block being defined.
449 BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
450
451 bool resolveForwardRefBlockAddresses();
452 };
453
454 bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
455 PerFunctionState *PFS, bool IsCall);
456
457 Value *checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
458 Value *Val, bool IsCall);
459
460 bool parseConstantValue(Type *Ty, Constant *&C);
461 bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
462 bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
463 return ParseValue(Ty, V, &PFS);
464 }
465
466 bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
467 PerFunctionState &PFS) {
468 Loc = Lex.getLoc();
469 return ParseValue(Ty, V, &PFS);
470 }
471
472 bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
473 bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
474 return ParseTypeAndValue(V, &PFS);
475 }
476 bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
477 Loc = Lex.getLoc();
478 return ParseTypeAndValue(V, PFS);
479 }
480 bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
481 PerFunctionState &PFS);
482 bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
483 LocTy Loc;
484 return ParseTypeAndBasicBlock(BB, Loc, PFS);
485 }
486
487
488 struct ParamInfo {
489 LocTy Loc;
490 Value *V;
491 AttributeSet Attrs;
492 ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
493 : Loc(loc), V(v), Attrs(attrs) {}
494 };
495 bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
496 PerFunctionState &PFS,
497 bool IsMustTailCall = false,
498 bool InVarArgsFunc = false);
499
500 bool
501 ParseOptionalOperandBundles(SmallVectorImpl<OperandBundleDef> &BundleList,
502 PerFunctionState &PFS);
503
504 bool ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
505 PerFunctionState &PFS);
506
507 // Constant Parsing.
508 bool ParseValID(ValID &ID, PerFunctionState *PFS = nullptr);
509 bool ParseGlobalValue(Type *Ty, Constant *&C);
510 bool ParseGlobalTypeAndValue(Constant *&V);
511 bool ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
512 Optional<unsigned> *InRangeOp = nullptr);
513 bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
514 bool ParseMetadataAsValue(Value *&V, PerFunctionState &PFS);
515 bool ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
516 PerFunctionState *PFS);
517 bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
518 bool ParseMDTuple(MDNode *&MD, bool IsDistinct = false);
519 bool ParseMDNode(MDNode *&N);
520 bool ParseMDNodeTail(MDNode *&N);
521 bool ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts);
522 bool ParseMetadataAttachment(unsigned &Kind, MDNode *&MD);
523 bool ParseInstructionMetadata(Instruction &Inst);
524 bool ParseGlobalObjectMetadataAttachment(GlobalObject &GO);
525 bool ParseOptionalFunctionMetadata(Function &F);
526
527 template <class FieldTy>
528 bool ParseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
529 template <class FieldTy> bool ParseMDField(StringRef Name, FieldTy &Result);
530 template <class ParserTy>
531 bool ParseMDFieldsImplBody(ParserTy parseField);
532 template <class ParserTy>
533 bool ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc);
534 bool ParseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
535
536#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
537 bool Parse##CLASS(MDNode *&Result, bool IsDistinct);
538#include "llvm/IR/Metadata.def"
539
540 // Function Parsing.
541 struct ArgInfo {
542 LocTy Loc;
543 Type *Ty;
544 AttributeSet Attrs;
545 std::string Name;
546 ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
547 : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
548 };
549 bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
550 bool ParseFunctionHeader(Function *&Fn, bool isDefine);
551 bool ParseFunctionBody(Function &Fn);
552 bool ParseBasicBlock(PerFunctionState &PFS);
553
554 enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
555
556 // Instruction Parsing. Each instruction parsing routine can return with a
557 // normal result, an error result, or return having eaten an extra comma.
558 enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
559 int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
560 PerFunctionState &PFS);
561 bool ParseCmpPredicate(unsigned &P, unsigned Opc);
562
563 bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
564 bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
565 bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
566 bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
567 bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
568 bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
569 bool ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS);
570 bool ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS);
571 bool ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS);
572 bool ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS);
573 bool ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS);
574
575 bool ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc,
576 unsigned OperandType);
577 bool ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc,
578 unsigned OperandType);
579 bool ParseLogical(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
580 bool ParseCompare(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
581 bool ParseCast(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
582 bool ParseSelect(Instruction *&Inst, PerFunctionState &PFS);
583 bool ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS);
584 bool ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS);
585 bool ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS);
586 bool ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS);
587 int ParsePHI(Instruction *&Inst, PerFunctionState &PFS);
588 bool ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS);
589 bool ParseCall(Instruction *&Inst, PerFunctionState &PFS,
590 CallInst::TailCallKind TCK);
591 int ParseAlloc(Instruction *&Inst, PerFunctionState &PFS);
592 int ParseLoad(Instruction *&Inst, PerFunctionState &PFS);
593 int ParseStore(Instruction *&Inst, PerFunctionState &PFS);
594 int ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS);
595 int ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS);
596 int ParseFence(Instruction *&Inst, PerFunctionState &PFS);
597 int ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS);
598 int ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS);
599 int ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS);
600
601 // Use-list order directives.
602 bool ParseUseListOrder(PerFunctionState *PFS = nullptr);
603 bool ParseUseListOrderBB();
604 bool ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
605 bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
606 };
607} // End llvm namespace
608
609#endif