1 // 2 // Copyright 2017 The ANGLE Project Authors. All rights reserved. 3 // Use of this source code is governed by a BSD-style license that can be 4 // found in the LICENSE file. 5 // 6 // IntermTraverse.h : base classes for AST traversers that walk the AST and 7 // also have the ability to transform it by replacing nodes. 8 9 #ifndef COMPILER_TRANSLATOR_TREEUTIL_INTERMTRAVERSE_H_ 10 #define COMPILER_TRANSLATOR_TREEUTIL_INTERMTRAVERSE_H_ 11 12 #include "compiler/translator/IntermNode.h" 13 #include "compiler/translator/tree_util/Visit.h" 14 15 namespace sh 16 { 17 18 class TCompiler; 19 class TSymbolTable; 20 class TSymbolUniqueId; 21 22 // For traversing the tree. User should derive from this class overriding the visit functions, 23 // and then pass an object of the subclass to a traverse method of a node. 24 // 25 // The traverse*() functions may also be overridden to do other bookkeeping on the tree to provide 26 // contextual information to the visit functions, such as whether the node is the target of an 27 // assignment. This is complex to maintain and so should only be done in special cases. 28 // 29 // When using this, just fill in the methods for nodes you want visited. 30 // Return false from a pre-visit to skip visiting that node's subtree. 31 // 32 // See also how to write AST transformations documentation: 33 // https://github.com/google/angle/blob/master/doc/WritingShaderASTTransformations.md 34 class TIntermTraverser : angle::NonCopyable 35 { 36 public: 37 POOL_ALLOCATOR_NEW_DELETE 38 TIntermTraverser(bool preVisitIn, 39 bool inVisitIn, 40 bool postVisitIn, 41 TSymbolTable *symbolTable = nullptr); 42 virtual ~TIntermTraverser(); 43 visitSymbol(TIntermSymbol * node)44 virtual void visitSymbol(TIntermSymbol *node) {} visitConstantUnion(TIntermConstantUnion * node)45 virtual void visitConstantUnion(TIntermConstantUnion *node) {} visitSwizzle(Visit visit,TIntermSwizzle * node)46 virtual bool visitSwizzle(Visit visit, TIntermSwizzle *node) { return true; } visitBinary(Visit visit,TIntermBinary * node)47 virtual bool visitBinary(Visit visit, TIntermBinary *node) { return true; } visitUnary(Visit visit,TIntermUnary * node)48 virtual bool visitUnary(Visit visit, TIntermUnary *node) { return true; } visitTernary(Visit visit,TIntermTernary * node)49 virtual bool visitTernary(Visit visit, TIntermTernary *node) { return true; } visitIfElse(Visit visit,TIntermIfElse * node)50 virtual bool visitIfElse(Visit visit, TIntermIfElse *node) { return true; } visitSwitch(Visit visit,TIntermSwitch * node)51 virtual bool visitSwitch(Visit visit, TIntermSwitch *node) { return true; } visitCase(Visit visit,TIntermCase * node)52 virtual bool visitCase(Visit visit, TIntermCase *node) { return true; } visitFunctionPrototype(TIntermFunctionPrototype * node)53 virtual void visitFunctionPrototype(TIntermFunctionPrototype *node) {} visitFunctionDefinition(Visit visit,TIntermFunctionDefinition * node)54 virtual bool visitFunctionDefinition(Visit visit, TIntermFunctionDefinition *node) 55 { 56 return true; 57 } visitAggregate(Visit visit,TIntermAggregate * node)58 virtual bool visitAggregate(Visit visit, TIntermAggregate *node) { return true; } visitBlock(Visit visit,TIntermBlock * node)59 virtual bool visitBlock(Visit visit, TIntermBlock *node) { return true; } visitGlobalQualifierDeclaration(Visit visit,TIntermGlobalQualifierDeclaration * node)60 virtual bool visitGlobalQualifierDeclaration(Visit visit, 61 TIntermGlobalQualifierDeclaration *node) 62 { 63 return true; 64 } visitDeclaration(Visit visit,TIntermDeclaration * node)65 virtual bool visitDeclaration(Visit visit, TIntermDeclaration *node) { return true; } visitLoop(Visit visit,TIntermLoop * node)66 virtual bool visitLoop(Visit visit, TIntermLoop *node) { return true; } visitBranch(Visit visit,TIntermBranch * node)67 virtual bool visitBranch(Visit visit, TIntermBranch *node) { return true; } visitPreprocessorDirective(TIntermPreprocessorDirective * node)68 virtual void visitPreprocessorDirective(TIntermPreprocessorDirective *node) {} 69 70 // The traverse functions contain logic for iterating over the children of the node 71 // and calling the visit functions in the appropriate places. They also track some 72 // context that may be used by the visit functions. 73 74 // The generic traverse() function is used for nodes that don't need special handling. 75 // It's templated in order to avoid virtual function calls, this gains around 2% compiler 76 // performance. 77 template <typename T> 78 void traverse(T *node); 79 80 // Specialized traverse functions are implemented for node types where traversal logic may need 81 // to be overridden or where some special bookkeeping needs to be done. 82 virtual void traverseBinary(TIntermBinary *node); 83 virtual void traverseUnary(TIntermUnary *node); 84 virtual void traverseFunctionDefinition(TIntermFunctionDefinition *node); 85 virtual void traverseAggregate(TIntermAggregate *node); 86 virtual void traverseBlock(TIntermBlock *node); 87 virtual void traverseLoop(TIntermLoop *node); 88 getMaxDepth()89 int getMaxDepth() const { return mMaxDepth; } 90 91 // If traversers need to replace nodes, they can add the replacements in 92 // mReplacements/mMultiReplacements during traversal and the user of the traverser should call 93 // this function after traversal to perform them. 94 // 95 // Compiler is used to validate the tree. Node is the same given to traverse(). Returns false 96 // if the tree is invalid after update. 97 ANGLE_NO_DISCARD bool updateTree(TCompiler *compiler, TIntermNode *node); 98 99 protected: 100 void setMaxAllowedDepth(int depth); 101 102 // Should only be called from traverse*() functions incrementDepth(TIntermNode * current)103 bool incrementDepth(TIntermNode *current) 104 { 105 mMaxDepth = std::max(mMaxDepth, static_cast<int>(mPath.size())); 106 mPath.push_back(current); 107 return mMaxDepth < mMaxAllowedDepth; 108 } 109 110 // Should only be called from traverse*() functions decrementDepth()111 void decrementDepth() { mPath.pop_back(); } 112 getCurrentTraversalDepth()113 int getCurrentTraversalDepth() const { return static_cast<int>(mPath.size()) - 1; } 114 115 // RAII helper for incrementDepth/decrementDepth 116 class ScopedNodeInTraversalPath 117 { 118 public: ScopedNodeInTraversalPath(TIntermTraverser * traverser,TIntermNode * current)119 ScopedNodeInTraversalPath(TIntermTraverser *traverser, TIntermNode *current) 120 : mTraverser(traverser) 121 { 122 mWithinDepthLimit = mTraverser->incrementDepth(current); 123 } ~ScopedNodeInTraversalPath()124 ~ScopedNodeInTraversalPath() { mTraverser->decrementDepth(); } 125 isWithinDepthLimit()126 bool isWithinDepthLimit() { return mWithinDepthLimit; } 127 128 private: 129 TIntermTraverser *mTraverser; 130 bool mWithinDepthLimit; 131 }; 132 // Optimized traversal functions for leaf nodes directly access ScopedNodeInTraversalPath. 133 friend void TIntermSymbol::traverse(TIntermTraverser *); 134 friend void TIntermConstantUnion::traverse(TIntermTraverser *); 135 friend void TIntermFunctionPrototype::traverse(TIntermTraverser *); 136 getParentNode()137 TIntermNode *getParentNode() const 138 { 139 return mPath.size() <= 1 ? nullptr : mPath[mPath.size() - 2u]; 140 } 141 142 // Return the nth ancestor of the node being traversed. getAncestorNode(0) == getParentNode() getAncestorNode(unsigned int n)143 TIntermNode *getAncestorNode(unsigned int n) const 144 { 145 if (mPath.size() > n + 1u) 146 { 147 return mPath[mPath.size() - n - 2u]; 148 } 149 return nullptr; 150 } 151 152 const TIntermBlock *getParentBlock() const; 153 getRootNode()154 TIntermNode *getRootNode() const 155 { 156 ASSERT(!mPath.empty()); 157 return mPath.front(); 158 } 159 160 void pushParentBlock(TIntermBlock *node); 161 void incrementParentBlockPos(); 162 void popParentBlock(); 163 164 // To replace a single node with multiple nodes in the parent aggregate. May be used with blocks 165 // but also with other nodes like declarations. 166 struct NodeReplaceWithMultipleEntry 167 { NodeReplaceWithMultipleEntryNodeReplaceWithMultipleEntry168 NodeReplaceWithMultipleEntry(TIntermAggregateBase *parentIn, 169 TIntermNode *originalIn, 170 TIntermSequence replacementsIn) 171 : parent(parentIn), original(originalIn), replacements(std::move(replacementsIn)) 172 {} 173 174 TIntermAggregateBase *parent; 175 TIntermNode *original; 176 TIntermSequence replacements; 177 }; 178 179 // Helper to insert statements in the parent block of the node currently being traversed. 180 // The statements will be inserted before the node being traversed once updateTree is called. 181 // Should only be called during PreVisit or PostVisit if called from block nodes. 182 // Note that two insertions to the same position in the same block are not supported. 183 void insertStatementsInParentBlock(const TIntermSequence &insertions); 184 185 // Same as above, but supports simultaneous insertion of statements before and after the node 186 // currently being traversed. 187 void insertStatementsInParentBlock(const TIntermSequence &insertionsBefore, 188 const TIntermSequence &insertionsAfter); 189 190 // Helper to insert a single statement. 191 void insertStatementInParentBlock(TIntermNode *statement); 192 193 // Explicitly specify where to insert statements. The statements are inserted before and after 194 // the specified position. The statements will be inserted once updateTree is called. Note that 195 // two insertions to the same position in the same block are not supported. 196 void insertStatementsInBlockAtPosition(TIntermBlock *parent, 197 size_t position, 198 const TIntermSequence &insertionsBefore, 199 const TIntermSequence &insertionsAfter); 200 201 enum class OriginalNode 202 { 203 BECOMES_CHILD, 204 IS_DROPPED 205 }; 206 207 void clearReplacementQueue(); 208 209 // Replace the node currently being visited with replacement. 210 void queueReplacement(TIntermNode *replacement, OriginalNode originalStatus); 211 // Explicitly specify a node to replace with replacement. 212 void queueReplacementWithParent(TIntermNode *parent, 213 TIntermNode *original, 214 TIntermNode *replacement, 215 OriginalNode originalStatus); 216 217 const bool preVisit; 218 const bool inVisit; 219 const bool postVisit; 220 221 int mMaxDepth; 222 int mMaxAllowedDepth; 223 224 bool mInGlobalScope; 225 226 // During traversing, save all the changes that need to happen into 227 // mReplacements/mMultiReplacements, then do them by calling updateTree(). 228 // Multi replacements are processed after single replacements. 229 std::vector<NodeReplaceWithMultipleEntry> mMultiReplacements; 230 231 TSymbolTable *mSymbolTable; 232 233 private: 234 // To insert multiple nodes into the parent block. 235 struct NodeInsertMultipleEntry 236 { NodeInsertMultipleEntryNodeInsertMultipleEntry237 NodeInsertMultipleEntry(TIntermBlock *_parent, 238 TIntermSequence::size_type _position, 239 TIntermSequence _insertionsBefore, 240 TIntermSequence _insertionsAfter) 241 : parent(_parent), 242 position(_position), 243 insertionsBefore(_insertionsBefore), 244 insertionsAfter(_insertionsAfter) 245 {} 246 247 TIntermBlock *parent; 248 TIntermSequence::size_type position; 249 TIntermSequence insertionsBefore; 250 TIntermSequence insertionsAfter; 251 }; 252 253 static bool CompareInsertion(const NodeInsertMultipleEntry &a, 254 const NodeInsertMultipleEntry &b); 255 256 // To replace a single node with another on the parent node 257 struct NodeUpdateEntry 258 { NodeUpdateEntryNodeUpdateEntry259 NodeUpdateEntry(TIntermNode *_parent, 260 TIntermNode *_original, 261 TIntermNode *_replacement, 262 bool _originalBecomesChildOfReplacement) 263 : parent(_parent), 264 original(_original), 265 replacement(_replacement), 266 originalBecomesChildOfReplacement(_originalBecomesChildOfReplacement) 267 {} 268 269 TIntermNode *parent; 270 TIntermNode *original; 271 TIntermNode *replacement; 272 bool originalBecomesChildOfReplacement; 273 }; 274 275 struct ParentBlock 276 { ParentBlockParentBlock277 ParentBlock(TIntermBlock *nodeIn, TIntermSequence::size_type posIn) 278 : node(nodeIn), pos(posIn) 279 {} 280 281 TIntermBlock *node; 282 TIntermSequence::size_type pos; 283 }; 284 285 std::vector<NodeInsertMultipleEntry> mInsertions; 286 std::vector<NodeUpdateEntry> mReplacements; 287 288 // All the nodes from root to the current node during traversing. 289 TVector<TIntermNode *> mPath; 290 291 // All the code blocks from the root to the current node's parent during traversal. 292 std::vector<ParentBlock> mParentBlockStack; 293 }; 294 295 // Traverser parent class that tracks where a node is a destination of a write operation and so is 296 // required to be an l-value. 297 class TLValueTrackingTraverser : public TIntermTraverser 298 { 299 public: 300 TLValueTrackingTraverser(bool preVisit, 301 bool inVisit, 302 bool postVisit, 303 TSymbolTable *symbolTable); ~TLValueTrackingTraverser()304 virtual ~TLValueTrackingTraverser() {} 305 306 void traverseBinary(TIntermBinary *node) final; 307 void traverseUnary(TIntermUnary *node) final; 308 void traverseAggregate(TIntermAggregate *node) final; 309 310 protected: isLValueRequiredHere()311 bool isLValueRequiredHere() const 312 { 313 return mOperatorRequiresLValue || mInFunctionCallOutParameter; 314 } 315 316 private: 317 // Track whether an l-value is required in the node that is currently being traversed by the 318 // surrounding operator. 319 // Use isLValueRequiredHere to check all conditions which require an l-value. setOperatorRequiresLValue(bool lValueRequired)320 void setOperatorRequiresLValue(bool lValueRequired) 321 { 322 mOperatorRequiresLValue = lValueRequired; 323 } operatorRequiresLValue()324 bool operatorRequiresLValue() const { return mOperatorRequiresLValue; } 325 326 // Track whether an l-value is required inside a function call. 327 void setInFunctionCallOutParameter(bool inOutParameter); 328 bool isInFunctionCallOutParameter() const; 329 330 bool mOperatorRequiresLValue; 331 bool mInFunctionCallOutParameter; 332 }; 333 334 } // namespace sh 335 336 #endif // COMPILER_TRANSLATOR_TREEUTIL_INTERMTRAVERSE_H_ 337