blob: 96ff6dfc9a9385715ab8ce05535e9b32202fc159 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 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
David Neto118188e2018-08-24 11:27:54 -040015#include "llvm/IR/Constants.h"
16#include "llvm/IR/Instructions.h"
17#include "llvm/IR/Module.h"
18#include "llvm/Pass.h"
19#include "llvm/Support/raw_ostream.h"
20#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040021
22using namespace llvm;
23
24#define DEBUG_TYPE "UndoTranslateSamplerFold"
25
26namespace {
27struct UndoTranslateSamplerFoldPass : public ModulePass {
28 static char ID;
29 UndoTranslateSamplerFoldPass() : ModulePass(ID) {}
30
31 bool runOnModule(Module &M) override;
32};
33}
34
35char UndoTranslateSamplerFoldPass::ID = 0;
36static RegisterPass<UndoTranslateSamplerFoldPass>
37 X("UndoTranslateSamplerFold", "Undo Transplate Sampler Fold Pass");
38
39namespace clspv {
40ModulePass *createUndoTranslateSamplerFoldPass() {
41 return new UndoTranslateSamplerFoldPass();
42}
43}
44
45bool UndoTranslateSamplerFoldPass::runOnModule(Module &M) {
46 auto F = M.getFunction("__translate_sampler_initializer");
47
48 if (!F) {
49 return false;
50 }
51
52 SmallVector<CallInst *, 1> BadCalls;
53
54 for (auto U : F->users()) {
55 if (auto CI = dyn_cast<CallInst>(U)) {
56 // Get the single argument to the translate sampler function.
57 auto Arg = CI->getArgOperand(0);
58
59 if (isa<ConstantInt>(Arg)) {
60 continue;
61 } else if (isa<SelectInst>(Arg)) {
62 BadCalls.push_back(CI);
63 } else {
64 Arg->print(errs());
65 llvm_unreachable(
66 "Unhandled argument to __translate_sampler_initializer!");
67 }
68 }
69 }
70
71 if (0 == BadCalls.size()) {
72 return false;
73 }
74
75 for (auto CI : BadCalls) {
76 // Get the single argument to the translate sampler function.
77 auto Arg = CI->getArgOperand(0);
78
79 if (auto Sel = dyn_cast<SelectInst>(Arg)) {
80 auto NewTrue = CallInst::Create(CI->getCalledFunction(),
81 Sel->getTrueValue(), "", CI);
82 auto NewFalse = CallInst::Create(CI->getCalledFunction(),
83 Sel->getFalseValue(), "", CI);
84 auto NewSel =
85 SelectInst::Create(Sel->getCondition(), NewTrue, NewFalse, "", CI);
86
87 CI->replaceAllUsesWith(NewSel);
88 CI->eraseFromParent();
89 Sel->eraseFromParent();
90 }
91 }
92
93 return true;
94}