Bug Summary

File:tools/llvm-exegesis/lib/Assembler.cpp
Warning:line 256, column 15
Dereference of null pointer (loaded from field 'CodeSize')

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 Assembler.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 -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~svn345461/build-llvm/tools/llvm-exegesis/lib -I /build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-exegesis/lib -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/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~svn345461/build-llvm/tools/llvm-exegesis/lib -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-exegesis/lib/Assembler.cpp -faddrsig
1//===-- Assembler.cpp -------------------------------------------*- 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#include "Assembler.h"
11
12#include "Target.h"
13#include "llvm/CodeGen/GlobalISel/CallLowering.h"
14#include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
15#include "llvm/CodeGen/MachineInstrBuilder.h"
16#include "llvm/CodeGen/MachineModuleInfo.h"
17#include "llvm/CodeGen/MachineRegisterInfo.h"
18#include "llvm/CodeGen/TargetInstrInfo.h"
19#include "llvm/CodeGen/TargetPassConfig.h"
20#include "llvm/CodeGen/TargetSubtargetInfo.h"
21#include "llvm/ExecutionEngine/SectionMemoryManager.h"
22#include "llvm/IR/LegacyPassManager.h"
23#include "llvm/MC/MCInstrInfo.h"
24#include "llvm/Support/MemoryBuffer.h"
25
26namespace llvm {
27namespace exegesis {
28
29static constexpr const char ModuleID[] = "ExegesisInfoTest";
30static constexpr const char FunctionID[] = "foo";
31
32static std::vector<llvm::MCInst>
33generateSnippetSetupCode(const ExegesisTarget &ET,
34 const llvm::MCSubtargetInfo *const MSI,
35 llvm::ArrayRef<RegisterValue> RegisterInitialValues,
36 bool &IsSnippetSetupComplete) {
37 IsSnippetSetupComplete = true;
38 std::vector<llvm::MCInst> Result;
39 for (const RegisterValue &RV : RegisterInitialValues) {
40 // Load a constant in the register.
41 const auto SetRegisterCode = ET.setRegTo(*MSI, RV.Register, RV.Value);
42 if (SetRegisterCode.empty())
43 IsSnippetSetupComplete = false;
44 Result.insert(Result.end(), SetRegisterCode.begin(), SetRegisterCode.end());
45 }
46 return Result;
47}
48
49// Small utility function to add named passes.
50static bool addPass(llvm::PassManagerBase &PM, llvm::StringRef PassName,
51 llvm::TargetPassConfig &TPC) {
52 const llvm::PassRegistry *PR = llvm::PassRegistry::getPassRegistry();
53 const llvm::PassInfo *PI = PR->getPassInfo(PassName);
54 if (!PI) {
55 llvm::errs() << " run-pass " << PassName << " is not registered.\n";
56 return true;
57 }
58
59 if (!PI->getNormalCtor()) {
60 llvm::errs() << " cannot create pass: " << PI->getPassName() << "\n";
61 return true;
62 }
63 llvm::Pass *P = PI->getNormalCtor()();
64 std::string Banner = std::string("After ") + std::string(P->getPassName());
65 PM.add(P);
66 TPC.printAndVerify(Banner);
67
68 return false;
69}
70
71// Creates a void(int8*) MachineFunction.
72static llvm::MachineFunction &
73createVoidVoidPtrMachineFunction(llvm::StringRef FunctionID,
74 llvm::Module *Module,
75 llvm::MachineModuleInfo *MMI) {
76 llvm::Type *const ReturnType = llvm::Type::getInt32Ty(Module->getContext());
77 llvm::Type *const MemParamType = llvm::PointerType::get(
78 llvm::Type::getInt8Ty(Module->getContext()), 0 /*default address space*/);
79 llvm::FunctionType *FunctionType =
80 llvm::FunctionType::get(ReturnType, {MemParamType}, false);
81 llvm::Function *const F = llvm::Function::Create(
82 FunctionType, llvm::GlobalValue::InternalLinkage, FunctionID, Module);
83 // Making sure we can create a MachineFunction out of this Function even if it
84 // contains no IR.
85 F->setIsMaterializable(true);
86 return MMI->getOrCreateMachineFunction(*F);
87}
88
89static void fillMachineFunction(llvm::MachineFunction &MF,
90 llvm::ArrayRef<unsigned> LiveIns,
91 llvm::ArrayRef<llvm::MCInst> Instructions) {
92 llvm::MachineBasicBlock *MBB = MF.CreateMachineBasicBlock();
93 MF.push_back(MBB);
94 for (const unsigned Reg : LiveIns)
95 MBB->addLiveIn(Reg);
96 const llvm::MCInstrInfo *MCII = MF.getTarget().getMCInstrInfo();
97 llvm::DebugLoc DL;
98 for (const llvm::MCInst &Inst : Instructions) {
99 const unsigned Opcode = Inst.getOpcode();
100 const llvm::MCInstrDesc &MCID = MCII->get(Opcode);
101 llvm::MachineInstrBuilder Builder = llvm::BuildMI(MBB, DL, MCID);
102 for (unsigned OpIndex = 0, E = Inst.getNumOperands(); OpIndex < E;
103 ++OpIndex) {
104 const llvm::MCOperand &Op = Inst.getOperand(OpIndex);
105 if (Op.isReg()) {
106 const bool IsDef = OpIndex < MCID.getNumDefs();
107 unsigned Flags = 0;
108 const llvm::MCOperandInfo &OpInfo = MCID.operands().begin()[OpIndex];
109 if (IsDef && !OpInfo.isOptionalDef())
110 Flags |= llvm::RegState::Define;
111 Builder.addReg(Op.getReg(), Flags);
112 } else if (Op.isImm()) {
113 Builder.addImm(Op.getImm());
114 } else if (!Op.isValid()) {
115 llvm_unreachable("Operand is not set")::llvm::llvm_unreachable_internal("Operand is not set", "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-exegesis/lib/Assembler.cpp"
, 115)
;
116 } else {
117 llvm_unreachable("Not yet implemented")::llvm::llvm_unreachable_internal("Not yet implemented", "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-exegesis/lib/Assembler.cpp"
, 117)
;
118 }
119 }
120 }
121 // Insert the return code.
122 const llvm::TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
123 if (TII->getReturnOpcode() < TII->getNumOpcodes()) {
124 llvm::BuildMI(MBB, DL, TII->get(TII->getReturnOpcode()));
125 } else {
126 llvm::MachineIRBuilder MIB(MF);
127 MIB.setMBB(*MBB);
128 MF.getSubtarget().getCallLowering()->lowerReturn(MIB, nullptr, {});
129 }
130}
131
132static std::unique_ptr<llvm::Module>
133createModule(const std::unique_ptr<llvm::LLVMContext> &Context,
134 const llvm::DataLayout DL) {
135 auto Module = llvm::make_unique<llvm::Module>(ModuleID, *Context);
136 Module->setDataLayout(DL);
137 return Module;
138}
139
140llvm::BitVector getFunctionReservedRegs(const llvm::TargetMachine &TM) {
141 std::unique_ptr<llvm::LLVMContext> Context =
142 llvm::make_unique<llvm::LLVMContext>();
143 std::unique_ptr<llvm::Module> Module =
144 createModule(Context, TM.createDataLayout());
145 std::unique_ptr<llvm::MachineModuleInfo> MMI =
146 llvm::make_unique<llvm::MachineModuleInfo>(&TM);
147 llvm::MachineFunction &MF =
148 createVoidVoidPtrMachineFunction(FunctionID, Module.get(), MMI.get());
149 // Saving reserved registers for client.
150 return MF.getSubtarget().getRegisterInfo()->getReservedRegs(MF);
151}
152
153void assembleToStream(const ExegesisTarget &ET,
154 std::unique_ptr<llvm::LLVMTargetMachine> TM,
155 llvm::ArrayRef<unsigned> LiveIns,
156 llvm::ArrayRef<RegisterValue> RegisterInitialValues,
157 llvm::ArrayRef<llvm::MCInst> Instructions,
158 llvm::raw_pwrite_stream &AsmStream) {
159 std::unique_ptr<llvm::LLVMContext> Context =
160 llvm::make_unique<llvm::LLVMContext>();
161 std::unique_ptr<llvm::Module> Module =
162 createModule(Context, TM->createDataLayout());
163 std::unique_ptr<llvm::MachineModuleInfo> MMI =
164 llvm::make_unique<llvm::MachineModuleInfo>(TM.get());
165 llvm::MachineFunction &MF =
166 createVoidVoidPtrMachineFunction(FunctionID, Module.get(), MMI.get());
167
168 // We need to instruct the passes that we're done with SSA and virtual
169 // registers.
170 auto &Properties = MF.getProperties();
171 Properties.set(llvm::MachineFunctionProperties::Property::NoVRegs);
172 Properties.reset(llvm::MachineFunctionProperties::Property::IsSSA);
173
174 for (const unsigned Reg : LiveIns)
175 MF.getRegInfo().addLiveIn(Reg);
176
177 bool IsSnippetSetupComplete;
178 std::vector<llvm::MCInst> Code =
179 generateSnippetSetupCode(ET, TM->getMCSubtargetInfo(),
180 RegisterInitialValues, IsSnippetSetupComplete);
181
182 Code.insert(Code.end(), Instructions.begin(), Instructions.end());
183
184 // If the snippet setup is not complete, we disable liveliness tracking. This
185 // means that we won't know what values are in the registers.
186 if (!IsSnippetSetupComplete)
187 Properties.reset(llvm::MachineFunctionProperties::Property::TracksLiveness);
188
189 // prologue/epilogue pass needs the reserved registers to be frozen, this
190 // is usually done by the SelectionDAGISel pass.
191 MF.getRegInfo().freezeReservedRegs(MF);
192
193 // Fill the MachineFunction from the instructions.
194 fillMachineFunction(MF, LiveIns, Code);
195
196 // We create the pass manager, run the passes to populate AsmBuffer.
197 llvm::MCContext &MCContext = MMI->getContext();
198 llvm::legacy::PassManager PM;
199
200 llvm::TargetLibraryInfoImpl TLII(llvm::Triple(Module->getTargetTriple()));
201 PM.add(new llvm::TargetLibraryInfoWrapperPass(TLII));
202
203 llvm::TargetPassConfig *TPC = TM->createPassConfig(PM);
204 PM.add(TPC);
205 PM.add(MMI.release());
206 TPC->printAndVerify("MachineFunctionGenerator::assemble");
207 // Add target-specific passes.
208 ET.addTargetSpecificPasses(PM);
209 TPC->printAndVerify("After ExegesisTarget::addTargetSpecificPasses");
210 // Adding the following passes:
211 // - machineverifier: checks that the MachineFunction is well formed.
212 // - prologepilog: saves and restore callee saved registers.
213 for (const char *PassName : {"machineverifier", "prologepilog"})
214 if (addPass(PM, PassName, *TPC))
215 llvm::report_fatal_error("Unable to add a mandatory pass");
216 TPC->setInitialized();
217
218 // AsmPrinter is responsible for generating the assembly into AsmBuffer.
219 if (TM->addAsmPrinter(PM, AsmStream, nullptr,
220 llvm::TargetMachine::CGFT_ObjectFile, MCContext))
221 llvm::report_fatal_error("Cannot add AsmPrinter passes");
222
223 PM.run(*Module); // Run all the passes
224}
225
226llvm::object::OwningBinary<llvm::object::ObjectFile>
227getObjectFromBuffer(llvm::StringRef InputData) {
228 // Storing the generated assembly into a MemoryBuffer that owns the memory.
229 std::unique_ptr<llvm::MemoryBuffer> Buffer =
230 llvm::MemoryBuffer::getMemBufferCopy(InputData);
231 // Create the ObjectFile from the MemoryBuffer.
232 std::unique_ptr<llvm::object::ObjectFile> Obj = llvm::cantFail(
233 llvm::object::ObjectFile::createObjectFile(Buffer->getMemBufferRef()));
234 // Returning both the MemoryBuffer and the ObjectFile.
235 return llvm::object::OwningBinary<llvm::object::ObjectFile>(
236 std::move(Obj), std::move(Buffer));
237}
238
239llvm::object::OwningBinary<llvm::object::ObjectFile>
240getObjectFromFile(llvm::StringRef Filename) {
241 return llvm::cantFail(llvm::object::ObjectFile::createObjectFile(Filename));
242}
243
244namespace {
245
246// Implementation of this class relies on the fact that a single object with a
247// single function will be loaded into memory.
248class TrackingSectionMemoryManager : public llvm::SectionMemoryManager {
249public:
250 explicit TrackingSectionMemoryManager(uintptr_t *CodeSize)
251 : CodeSize(CodeSize) {}
252
253 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
254 unsigned SectionID,
255 llvm::StringRef SectionName) override {
256 *CodeSize = Size;
Dereference of null pointer (loaded from field 'CodeSize')
257 return llvm::SectionMemoryManager::allocateCodeSection(
258 Size, Alignment, SectionID, SectionName);
259 }
260
261private:
262 uintptr_t *const CodeSize = nullptr;
263};
264
265} // namespace
266
267ExecutableFunction::ExecutableFunction(
268 std::unique_ptr<llvm::LLVMTargetMachine> TM,
269 llvm::object::OwningBinary<llvm::object::ObjectFile> &&ObjectFileHolder)
270 : Context(llvm::make_unique<llvm::LLVMContext>()) {
271 assert(ObjectFileHolder.getBinary() && "cannot create object file")((ObjectFileHolder.getBinary() && "cannot create object file"
) ? static_cast<void> (0) : __assert_fail ("ObjectFileHolder.getBinary() && \"cannot create object file\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-exegesis/lib/Assembler.cpp"
, 271, __PRETTY_FUNCTION__))
;
272 // Initializing the execution engine.
273 // We need to use the JIT EngineKind to be able to add an object file.
274 LLVMLinkInMCJIT();
275 uintptr_t CodeSize = 0;
276 std::string Error;
277 ExecEngine.reset(
278 llvm::EngineBuilder(createModule(Context, TM->createDataLayout()))
279 .setErrorStr(&Error)
280 .setMCPU(TM->getTargetCPU())
281 .setEngineKind(llvm::EngineKind::JIT)
282 .setMCJITMemoryManager(
283 llvm::make_unique<TrackingSectionMemoryManager>(&CodeSize))
284 .create(TM.release()));
285 if (!ExecEngine)
286 llvm::report_fatal_error(Error);
287 // Adding the generated object file containing the assembled function.
288 // The ExecutionEngine makes sure the object file is copied into an
289 // executable page.
290 ExecEngine->addObjectFile(std::move(ObjectFileHolder));
291 // Fetching function bytes.
292 FunctionBytes =
293 llvm::StringRef(reinterpret_cast<const char *>(
294 ExecEngine->getFunctionAddress(FunctionID)),
295 CodeSize);
296}
297
298} // namespace exegesis
299} // namespace llvm