ModuleTest.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //===- unittests/IR/ModuleTest.cpp - Module unit tests --------------------===//
  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. #include "llvm/IR/Module.h"
  9. #include "llvm/IR/GlobalVariable.h"
  10. #include "llvm/Pass.h"
  11. #include "llvm/Support/RandomNumberGenerator.h"
  12. #include "gtest/gtest.h"
  13. #include <random>
  14. using namespace llvm;
  15. namespace {
  16. bool sortByName(const GlobalVariable &L, const GlobalVariable &R) {
  17. return L.getName() < R.getName();
  18. }
  19. bool sortByNameReverse(const GlobalVariable &L, const GlobalVariable &R) {
  20. return sortByName(R, L);
  21. }
  22. TEST(ModuleTest, sortGlobalsByName) {
  23. LLVMContext Context;
  24. for (auto compare : {&sortByName, &sortByNameReverse}) {
  25. Module M("M", Context);
  26. Type *T = Type::getInt8Ty(Context);
  27. GlobalValue::LinkageTypes L = GlobalValue::ExternalLinkage;
  28. (void)new GlobalVariable(M, T, false, L, nullptr, "A");
  29. (void)new GlobalVariable(M, T, false, L, nullptr, "F");
  30. (void)new GlobalVariable(M, T, false, L, nullptr, "G");
  31. (void)new GlobalVariable(M, T, false, L, nullptr, "E");
  32. (void)new GlobalVariable(M, T, false, L, nullptr, "B");
  33. (void)new GlobalVariable(M, T, false, L, nullptr, "H");
  34. (void)new GlobalVariable(M, T, false, L, nullptr, "C");
  35. (void)new GlobalVariable(M, T, false, L, nullptr, "D");
  36. // Sort the globals by name.
  37. EXPECT_FALSE(std::is_sorted(M.global_begin(), M.global_end(), compare));
  38. M.getGlobalList().sort(compare);
  39. EXPECT_TRUE(std::is_sorted(M.global_begin(), M.global_end(), compare));
  40. }
  41. }
  42. TEST(ModuleTest, randomNumberGenerator) {
  43. LLVMContext Context;
  44. static char ID;
  45. struct DummyPass : ModulePass {
  46. DummyPass() : ModulePass(ID) {}
  47. bool runOnModule(Module &) { return true; }
  48. } DP;
  49. Module M("R", Context);
  50. std::uniform_int_distribution<int> dist;
  51. const size_t NBCheck = 10;
  52. std::array<int, NBCheck> RandomStreams[2];
  53. for (auto &RandomStream : RandomStreams) {
  54. std::unique_ptr<RandomNumberGenerator> RNG = M.createRNG(&DP);
  55. std::generate(RandomStream.begin(), RandomStream.end(),
  56. [&]() { return dist(*RNG); });
  57. }
  58. EXPECT_TRUE(std::equal(RandomStreams[0].begin(), RandomStreams[0].end(),
  59. RandomStreams[1].begin()));
  60. }
  61. } // end namespace