void MemoryInstrumenter::instrumentGlobals(Module &M) {
  TargetData &TD = getAnalysis<TargetData>();
  IDAssigner &IDA = getAnalysis<IDAssigner>();

  // Function HookGlobalsAlloc contains only one basic block.
  // The BB iterates through all global variables, and calls HookMemAlloc
  // for each of them.
  BasicBlock *BB = BasicBlock::Create(M.getContext(), "entry",
                                      GlobalsAllocHook);
  Instruction *Ret = ReturnInst::Create(M.getContext(), BB);

  for (Module::global_iterator GI = M.global_begin(), E = M.global_end();
       GI != E; ++GI) {
    // We are going to delete llvm.global_ctors.
    // Therefore, don't instrument it.
    if (GI->getName() == "llvm.global_ctors")
      continue;
    // Prevent global variables from sharing the same address, because it
    // breaks the assumption that global variables do not alias.
    // The same goes to functions.
    if (GI->hasUnnamedAddr()) {
      GI->setUnnamedAddr(false);
    }
    uint64_t TypeSize = TD.getTypeStoreSize(GI->getType()->getElementType());
    instrumentMemoryAllocation(GI,
                               ConstantInt::get(LongType, TypeSize),
                               NULL,
                               Ret);
    instrumentPointer(GI, NULL, Ret);
  }

  for (Module::iterator F = M.begin(); F != M.end(); ++F) {
    // These hooks added by us don't have a value ID.
    if (MemAllocHook == F || MainArgsAllocHook == F || TopLevelHook == F ||
        AddrTakenHook == F || CallHook == F || ReturnHook == F ||
        GlobalsAllocHook == F || MemHooksIniter == F || AfterForkHook == F ||
        BeforeForkHook == F) {
      continue;
    }
    // InvalidID: maybe this is inserted by alias checker in hybrid mode.
    if (IDA.getValueID(F) == IDAssigner::InvalidID)
      continue;
    // Ignore intrinsic functions because we cannot take the address of
    // an intrinsic. Also, no function pointers will point to instrinsic
    // functions.
    if (F->isIntrinsic())
      continue;
    // Prevent functions from sharing the same address.
    if (F->hasUnnamedAddr()) {
      F->setUnnamedAddr(false);
    }
    uint64_t TypeSize = TD.getTypeStoreSize(F->getType());
    assert(TypeSize == TD.getPointerSize());
    instrumentMemoryAllocation(F,
                               ConstantInt::get(LongType, TypeSize),
                               NULL,
                               Ret);
    instrumentPointer(F, NULL, Ret);
  }
}