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 // Returns what child index is currently being visited. For example when visiting the children 153 // of an aggregate, it can be used to find out which argument of the parent (aggregate) node 154 // they correspond to. Only valid in the PreVisit call of the child. getParentChildIndex(Visit visit)155 size_t getParentChildIndex(Visit visit) const 156 { 157 ASSERT(visit == PreVisit); 158 return mCurrentChildIndex; 159 } 160 // Returns what child index has just been processed. Only valid in the InVisit and PostVisit 161 // calls of the parent node. getLastTraversedChildIndex(Visit visit)162 size_t getLastTraversedChildIndex(Visit visit) const 163 { 164 ASSERT(visit != PreVisit); 165 return mCurrentChildIndex; 166 } 167 168 const TIntermBlock *getParentBlock() const; 169 getRootNode()170 TIntermNode *getRootNode() const 171 { 172 ASSERT(!mPath.empty()); 173 return mPath.front(); 174 } 175 176 void pushParentBlock(TIntermBlock *node); 177 void incrementParentBlockPos(); 178 void popParentBlock(); 179 180 // To replace a single node with multiple nodes in the parent aggregate. May be used with blocks 181 // but also with other nodes like declarations. 182 struct NodeReplaceWithMultipleEntry 183 { NodeReplaceWithMultipleEntryNodeReplaceWithMultipleEntry184 NodeReplaceWithMultipleEntry(TIntermAggregateBase *parentIn, 185 TIntermNode *originalIn, 186 TIntermSequence &&replacementsIn) 187 : parent(parentIn), original(originalIn), replacements(std::move(replacementsIn)) 188 {} 189 190 TIntermAggregateBase *parent; 191 TIntermNode *original; 192 TIntermSequence replacements; 193 }; 194 195 // Helper to insert statements in the parent block of the node currently being traversed. 196 // The statements will be inserted before the node being traversed once updateTree is called. 197 // Should only be called during PreVisit or PostVisit if called from block nodes. 198 // Note that two insertions to the same position in the same block are not supported. 199 void insertStatementsInParentBlock(const TIntermSequence &insertions); 200 201 // Same as above, but supports simultaneous insertion of statements before and after the node 202 // currently being traversed. 203 void insertStatementsInParentBlock(const TIntermSequence &insertionsBefore, 204 const TIntermSequence &insertionsAfter); 205 206 // Helper to insert a single statement. 207 void insertStatementInParentBlock(TIntermNode *statement); 208 209 // Explicitly specify where to insert statements. The statements are inserted before and after 210 // the specified position. The statements will be inserted once updateTree is called. Note that 211 // two insertions to the same position in the same block are not supported. 212 void insertStatementsInBlockAtPosition(TIntermBlock *parent, 213 size_t position, 214 const TIntermSequence &insertionsBefore, 215 const TIntermSequence &insertionsAfter); 216 217 enum class OriginalNode 218 { 219 BECOMES_CHILD, 220 IS_DROPPED 221 }; 222 223 void clearReplacementQueue(); 224 225 // Replace the node currently being visited with replacement. 226 void queueReplacement(TIntermNode *replacement, OriginalNode originalStatus); 227 // Explicitly specify a node to replace with replacement. 228 void queueReplacementWithParent(TIntermNode *parent, 229 TIntermNode *original, 230 TIntermNode *replacement, 231 OriginalNode originalStatus); 232 233 const bool preVisit; 234 const bool inVisit; 235 const bool postVisit; 236 237 int mMaxDepth; 238 int mMaxAllowedDepth; 239 240 bool mInGlobalScope; 241 242 // During traversing, save all the changes that need to happen into 243 // mReplacements/mMultiReplacements, then do them by calling updateTree(). 244 // Multi replacements are processed after single replacements. 245 std::vector<NodeReplaceWithMultipleEntry> mMultiReplacements; 246 247 TSymbolTable *mSymbolTable; 248 249 private: 250 // To insert multiple nodes into the parent block. 251 struct NodeInsertMultipleEntry 252 { NodeInsertMultipleEntryNodeInsertMultipleEntry253 NodeInsertMultipleEntry(TIntermBlock *_parent, 254 TIntermSequence::size_type _position, 255 TIntermSequence _insertionsBefore, 256 TIntermSequence _insertionsAfter) 257 : parent(_parent), 258 position(_position), 259 insertionsBefore(_insertionsBefore), 260 insertionsAfter(_insertionsAfter) 261 {} 262 263 TIntermBlock *parent; 264 TIntermSequence::size_type position; 265 TIntermSequence insertionsBefore; 266 TIntermSequence insertionsAfter; 267 }; 268 269 static bool CompareInsertion(const NodeInsertMultipleEntry &a, 270 const NodeInsertMultipleEntry &b); 271 272 // To replace a single node with another on the parent node 273 struct NodeUpdateEntry 274 { NodeUpdateEntryNodeUpdateEntry275 NodeUpdateEntry(TIntermNode *_parent, 276 TIntermNode *_original, 277 TIntermNode *_replacement, 278 bool _originalBecomesChildOfReplacement) 279 : parent(_parent), 280 original(_original), 281 replacement(_replacement), 282 originalBecomesChildOfReplacement(_originalBecomesChildOfReplacement) 283 {} 284 285 TIntermNode *parent; 286 TIntermNode *original; 287 TIntermNode *replacement; 288 bool originalBecomesChildOfReplacement; 289 }; 290 291 struct ParentBlock 292 { ParentBlockParentBlock293 ParentBlock(TIntermBlock *nodeIn, TIntermSequence::size_type posIn) 294 : node(nodeIn), pos(posIn) 295 {} 296 297 TIntermBlock *node; 298 TIntermSequence::size_type pos; 299 }; 300 301 std::vector<NodeInsertMultipleEntry> mInsertions; 302 std::vector<NodeUpdateEntry> mReplacements; 303 304 // All the nodes from root to the current node during traversing. 305 TVector<TIntermNode *> mPath; 306 // The current child of parent being traversed. 307 size_t mCurrentChildIndex; 308 309 // All the code blocks from the root to the current node's parent during traversal. 310 std::vector<ParentBlock> mParentBlockStack; 311 }; 312 313 // Traverser parent class that tracks where a node is a destination of a write operation and so is 314 // required to be an l-value. 315 class TLValueTrackingTraverser : public TIntermTraverser 316 { 317 public: 318 TLValueTrackingTraverser(bool preVisit, 319 bool inVisit, 320 bool postVisit, 321 TSymbolTable *symbolTable); ~TLValueTrackingTraverser()322 ~TLValueTrackingTraverser() override {} 323 324 void traverseBinary(TIntermBinary *node) final; 325 void traverseUnary(TIntermUnary *node) final; 326 void traverseAggregate(TIntermAggregate *node) final; 327 328 protected: isLValueRequiredHere()329 bool isLValueRequiredHere() const 330 { 331 return mOperatorRequiresLValue || mInFunctionCallOutParameter; 332 } 333 334 private: 335 // Track whether an l-value is required in the node that is currently being traversed by the 336 // surrounding operator. 337 // Use isLValueRequiredHere to check all conditions which require an l-value. setOperatorRequiresLValue(bool lValueRequired)338 void setOperatorRequiresLValue(bool lValueRequired) 339 { 340 mOperatorRequiresLValue = lValueRequired; 341 } operatorRequiresLValue()342 bool operatorRequiresLValue() const { return mOperatorRequiresLValue; } 343 344 // Track whether an l-value is required inside a function call. 345 void setInFunctionCallOutParameter(bool inOutParameter); 346 bool isInFunctionCallOutParameter() const; 347 348 bool mOperatorRequiresLValue; 349 bool mInFunctionCallOutParameter; 350 }; 351 352 } // namespace sh 353 354 #endif // COMPILER_TRANSLATOR_TREEUTIL_INTERMTRAVERSE_H_ 355