blob: 1629df2134ca43b1501c65b31e9312c2ca998bf5 [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
Diego Novilloa4c44fa2019-04-11 10:56:15 -040026#include "Passes.h"
27
David Neto8e138142018-05-29 10:19:21 -040028using namespace llvm;
29
30#define DEBUG_TYPE "rewriteconstantexpressions"
31
32namespace {
33
34llvm::cl::opt<bool>
35 no_zero_allocas("no-zero-allocas", llvm::cl::init(false),
36 llvm::cl::desc("Don't zero-initialize stack variables"));
37
38struct ZeroInitializeAllocasPass : public ModulePass {
39 static char ID;
40 ZeroInitializeAllocasPass() : ModulePass(ID) {}
41
42 bool runOnModule(Module &M) override;
43};
44} // namespace
45
46char ZeroInitializeAllocasPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -040047INITIALIZE_PASS(ZeroInitializeAllocasPass, "ZeroInitializeAllocasPass",
48 "Zero-initialize stack variables", false, false)
David Neto8e138142018-05-29 10:19:21 -040049
50namespace clspv {
51llvm::ModulePass *createZeroInitializeAllocasPass() {
52 return new ZeroInitializeAllocasPass();
53}
54} // namespace clspv
55
56bool ZeroInitializeAllocasPass::runOnModule(Module &M) {
57 bool Changed = false;
58 if (no_zero_allocas)
59 return Changed;
60
61 SmallVector<AllocaInst *, 8> WorkList;
62 for (Function &F : M) {
63 for (BasicBlock &BB : F) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040064 for (auto iter = BB.begin(); iter != BB.end(); ++iter) {
David Neto8e138142018-05-29 10:19:21 -040065 if (auto *alloca = dyn_cast<AllocaInst>(&*iter)) {
66 WorkList.push_back(alloca);
67 }
68 }
69 }
70 }
71
72 for (AllocaInst *alloca : WorkList) {
73 auto *valueTy = alloca->getType()->getPointerElementType();
alan-baker1c327202020-05-19 11:08:33 -040074 auto *store = new StoreInst(Constant::getNullValue(valueTy), alloca, false,
75 Align(alloca->getAlignment()));
David Neto8e138142018-05-29 10:19:21 -040076 store->insertAfter(alloca);
77 }
78
79 return Changed;
80}