| 1 |
//===- ModuleUtilsTest.cpp - Unit tests for Module utility ----===// |
| 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 |
#include "llvm/Transforms/Utils/ModuleUtils.h" |
| 10 |
#include "llvm/ADT/StringRef.h" |
| 11 |
#include "llvm/AsmParser/Parser.h" |
| 12 |
#include "llvm/IR/LLVMContext.h" |
| 13 |
#include "llvm/IR/Module.h" |
| 14 |
#include "llvm/Support/SourceMgr.h" |
| 15 |
#include "gtest/gtest.h" |
| 16 |
|
| 17 |
using namespace llvm; |
| 18 |
|
| 19 |
static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) { |
| 20 |
SMDiagnostic Err; |
| 21 |
std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C); |
| 22 |
if (!Mod) |
| 23 |
Err.print("ModuleUtilsTest", errs()); |
| 24 |
return Mod; |
| 25 |
} |
| 26 |
|
| 27 |
static int getUsedListSize(Module &M, StringRef Name) { |
| 28 |
auto *UsedList = M.getGlobalVariable(Name); |
| 29 |
if (!UsedList) |
| 30 |
return 0; |
| 31 |
auto *UsedListBaseArrayType = cast<ArrayType>(UsedList->getValueType()); |
| 32 |
return UsedListBaseArrayType->getNumElements(); |
| 33 |
} |
| 34 |
|
| 35 |
TEST(ModuleUtils, AppendToUsedList1) { |
| 36 |
LLVMContext C; |
| 37 |
|
| 38 |
std::unique_ptr<Module> M = parseIR( |
| 39 |
C, R"(@x = addrspace(4) global [2 x i32] zeroinitializer, align 4)"); |
| 40 |
SmallVector<GlobalValue *, 2> Globals; |
| 41 |
for (auto &G : M->globals()) { |
| 42 |
Globals.push_back(&G); |
| 43 |
} |
| 44 |
EXPECT_EQ(0, getUsedListSize(*M, "llvm.compiler.used")); |
| 45 |
appendToCompilerUsed(*M, Globals); |
| 46 |
EXPECT_EQ(1, getUsedListSize(*M, "llvm.compiler.used")); |
| 47 |
|
| 48 |
EXPECT_EQ(0, getUsedListSize(*M, "llvm.used")); |
| 49 |
appendToUsed(*M, Globals); |
| 50 |
EXPECT_EQ(1, getUsedListSize(*M, "llvm.used")); |
| 51 |
} |
| 52 |
|
| 53 |
TEST(ModuleUtils, AppendToUsedList2) { |
| 54 |
LLVMContext C; |
| 55 |
|
| 56 |
std::unique_ptr<Module> M = |
| 57 |
parseIR(C, R"(@x = global [2 x i32] zeroinitializer, align 4)"); |
| 58 |
SmallVector<GlobalValue *, 2> Globals; |
| 59 |
for (auto &G : M->globals()) { |
| 60 |
Globals.push_back(&G); |
| 61 |
} |
| 62 |
EXPECT_EQ(0, getUsedListSize(*M, "llvm.compiler.used")); |
| 63 |
appendToCompilerUsed(*M, Globals); |
| 64 |
EXPECT_EQ(1, getUsedListSize(*M, "llvm.compiler.used")); |
| 65 |
|
| 66 |
EXPECT_EQ(0, getUsedListSize(*M, "llvm.used")); |
| 67 |
appendToUsed(*M, Globals); |
| 68 |
EXPECT_EQ(1, getUsedListSize(*M, "llvm.used")); |
| 69 |
} |