blob: 17d5032ef4521771f4f0a77e08eb773137bf3e45 [file] [log] [blame]
David Neto8e138142018-05-29 10:19:21 -04001// Copyright 2018 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include <utility>
16
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/UniqueVector.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/Module.h"
22#include "llvm/Pass.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/raw_ostream.h"
25
26using namespace llvm;
27
28#define DEBUG_TYPE "rewriteconstantexpressions"
29
30namespace {
31
32llvm::cl::opt<bool>
33 no_zero_allocas("no-zero-allocas", llvm::cl::init(false),
34 llvm::cl::desc("Don't zero-initialize stack variables"));
35
36struct ZeroInitializeAllocasPass : public ModulePass {
37 static char ID;
38 ZeroInitializeAllocasPass() : ModulePass(ID) {}
39
40 bool runOnModule(Module &M) override;
41};
42} // namespace
43
44char ZeroInitializeAllocasPass::ID = 0;
45static RegisterPass<ZeroInitializeAllocasPass>
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040046 X("ZeroInitializeAllocasPass", "Zero-initialize stack variables");
David Neto8e138142018-05-29 10:19:21 -040047
48namespace clspv {
49llvm::ModulePass *createZeroInitializeAllocasPass() {
50 return new ZeroInitializeAllocasPass();
51}
52} // namespace clspv
53
54bool ZeroInitializeAllocasPass::runOnModule(Module &M) {
55 bool Changed = false;
56 if (no_zero_allocas)
57 return Changed;
58
59 SmallVector<AllocaInst *, 8> WorkList;
60 for (Function &F : M) {
61 for (BasicBlock &BB : F) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040062 for (auto iter = BB.begin(); iter != BB.end(); ++iter) {
David Neto8e138142018-05-29 10:19:21 -040063 if (auto *alloca = dyn_cast<AllocaInst>(&*iter)) {
64 WorkList.push_back(alloca);
65 }
66 }
67 }
68 }
69
70 for (AllocaInst *alloca : WorkList) {
71 auto *valueTy = alloca->getType()->getPointerElementType();
72 auto *store = new StoreInst(Constant::getNullValue(valueTy), alloca);
73 store->insertAfter(alloca);
74 }
75
76 return Changed;
77}