| 1 | //===----------------------------------------------------------------------===// |
| 2 | // |
| 3 | // Copyright (c) 2012, 2013, 2015, 2017, 2018, 2019, 2020 The University of Utah |
| 4 | // All rights reserved. |
| 5 | // |
| 6 | // This file is distributed under the University of Illinois Open Source |
| 7 | // License. See the file COPYING for details. |
| 8 | // |
| 9 | //===----------------------------------------------------------------------===// |
| 10 | |
| 11 | #if HAVE_CONFIG_H |
| 12 | # include <config.h> |
| 13 | #endif |
| 14 | |
| 15 | #include "ReduceArrayDim.h" |
| 16 | |
| 17 | #include <sstream> |
| 18 | #include <cctype> |
| 19 | #include "clang/AST/RecursiveASTVisitor.h" |
| 20 | #include "clang/AST/ASTContext.h" |
| 21 | #include "clang/Basic/SourceManager.h" |
| 22 | |
| 23 | #include "TransformationManager.h" |
| 24 | |
| 25 | using namespace clang; |
| 26 | |
| 27 | static const char *DescriptionMsg = |
| 28 | "Reduce the dimension of an array. Each transformation iteration \ |
| 29 | reduces one dimension in the following way: \n\ |
| 30 | int a[2][3][4]; \n\ |
| 31 | void foo(void) {... a[1][2][3] ... }\n\ |
| 32 | ===> \n\ |
| 33 | int a[2][3 * 4]; \n\ |
| 34 | void foo(void) {... a[1][3 * 2 + 3] ... }\n\ |
| 35 | The binary operations will be computed to constant during the \ |
| 36 | transformation if possible. Array fields are not handled right now. \ |
| 37 | Also, this pass only works with ConstantArrayType and IncompleteArrayType.\n"; |
| 38 | |
| 39 | static RegisterTransformation<ReduceArrayDim> |
| 40 | Trans("reduce-array-dim", DescriptionMsg); |
| 41 | |
| 42 | class ReduceArrayDimCollectionVisitor : public |
| 43 | RecursiveASTVisitor<ReduceArrayDimCollectionVisitor> { |
| 44 | |
| 45 | public: |
| 46 | |
| 47 | explicit ReduceArrayDimCollectionVisitor(ReduceArrayDim *Instance) |
| 48 | : ConsumerInstance(Instance) |
| 49 | { } |
| 50 | |
| 51 | bool VisitVarDecl(VarDecl *VD); |
| 52 | |
| 53 | private: |
| 54 | |
| 55 | ReduceArrayDim *ConsumerInstance; |
| 56 | }; |
| 57 | |
| 58 | bool ReduceArrayDimCollectionVisitor::VisitVarDecl(VarDecl *VD) |
| 59 | { |
| 60 | ConsumerInstance->addOneVar(VD); |
| 61 | return true; |
| 62 | } |
| 63 | |
| 64 | class ReduceArrayDimRewriteVisitor : public |
| 65 | RecursiveASTVisitor<ReduceArrayDimRewriteVisitor> { |
| 66 | |
| 67 | public: |
| 68 | |
| 69 | explicit ReduceArrayDimRewriteVisitor(ReduceArrayDim *Instance) |
| 70 | : ConsumerInstance(Instance) |
| 71 | { } |
| 72 | |
| 73 | bool VisitVarDecl(VarDecl *VD); |
| 74 | |
| 75 | bool VisitArraySubscriptExpr(ArraySubscriptExpr *DRE); |
| 76 | |
| 77 | private: |
| 78 | |
| 79 | ReduceArrayDim *ConsumerInstance; |
| 80 | |
| 81 | }; |
| 82 | |
| 83 | bool ReduceArrayDimRewriteVisitor::VisitVarDecl(VarDecl *VD) |
| 84 | { |
| 85 | const VarDecl *CanonicalVD = VD->getCanonicalDecl(); |
| 86 | if (CanonicalVD != ConsumerInstance->TheVarDecl) |
| 87 | return true; |
| 88 | |
| 89 | ConsumerInstance->rewriteOneVarDecl(VD); |
| 90 | return true; |
| 91 | } |
| 92 | |
| 93 | bool ReduceArrayDimRewriteVisitor::VisitArraySubscriptExpr( |
| 94 | ArraySubscriptExpr *ASE) |
| 95 | { |
| 96 | ConsumerInstance->handleOneArraySubscriptExpr(ASE); |
| 97 | return true; |
| 98 | } |
| 99 | |
| 100 | void ReduceArrayDim::Initialize(ASTContext &context) |
| 101 | { |
| 102 | Transformation::Initialize(context); |
| 103 | CollectionVisitor = new ReduceArrayDimCollectionVisitor(this); |
| 104 | RewriteVisitor = new ReduceArrayDimRewriteVisitor(this); |
| 105 | } |
| 106 | |
| 107 | bool ReduceArrayDim::HandleTopLevelDecl(DeclGroupRef D) |
| 108 | { |
| 109 | for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { |
| 110 | CollectionVisitor->TraverseDecl(*I); |
| 111 | } |
| 112 | return true; |
| 113 | } |
| 114 | |
| 115 | void ReduceArrayDim::HandleTranslationUnit(ASTContext &Ctx) |
| 116 | { |
| 117 | if (QueryInstanceOnly) |
| 118 | return; |
| 119 | |
| 120 | if (TransformationCounter > ValidInstanceNum) { |
| 121 | TransError = TransMaxInstanceError; |
| 122 | return; |
| 123 | } |
| 124 | |
| 125 | TransAssert(RewriteVisitor && "NULL RewriteVisitor!"); |
| 126 | Ctx.getDiagnostics().setSuppressAllDiagnostics(false); |
| 127 | TransAssert(TheVarDecl && "NULL TheVarDecl!"); |
| 128 | |
| 129 | RewriteVisitor->TraverseDecl(Ctx.getTranslationUnitDecl()); |
| 130 | if (!Rewritten) { |
| 131 | TransError = TransNoTextModificationError; |
| 132 | return; |
| 133 | } |
| 134 | |
| 135 | if (Ctx.getDiagnostics().hasErrorOccurred() || |
| 136 | Ctx.getDiagnostics().hasFatalErrorOccurred()) |
| 137 | TransError = TransInternalError; |
| 138 | } |
| 139 | |
| 140 | void ReduceArrayDim::addOneVar(const VarDecl *VD) |
| 141 | { |
| 142 | if (isInIncludedFile(VD)) |
| 143 | return; |
| 144 | |
| 145 | const Type *Ty = VD->getType().getTypePtr(); |
| 146 | const ArrayType *ArrayTy = dyn_cast<ArrayType>(Ty); |
| 147 | if (!ArrayTy) |
| 148 | return; |
| 149 | |
| 150 | unsigned int ArrayDim = getArrayDimension(ArrayTy); |
| 151 | if (ArrayDim <= 1) |
| 152 | return; |
| 153 | |
| 154 | // Skip these two array types |
| 155 | if (dyn_cast<DependentSizedArrayType>(ArrayTy) || |
| 156 | dyn_cast<VariableArrayType>(ArrayTy)) |
| 157 | return; |
| 158 | |
| 159 | const VarDecl *CanonicalVD = VD->getCanonicalDecl(); |
| 160 | if (VisitedVarDecls.count(CanonicalVD)) |
| 161 | return; |
| 162 | |
| 163 | VisitedVarDecls.insert(CanonicalVD); |
| 164 | ValidInstanceNum++; |
| 165 | if (TransformationCounter == ValidInstanceNum) { |
| 166 | TheVarDecl = CanonicalVD; |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | // This function doesn't consider nested brackets, which won't |
| 171 | // exist for the definitions of ConstantArrayType and IncompleteArrayType |
| 172 | void ReduceArrayDim::getBracketLocPairs(const VarDecl *VD, |
| 173 | unsigned int Dim, |
| 174 | BracketLocPairVector &BPVec) |
| 175 | { |
| 176 | SourceLocation StartLoc = VD->getLocation(); |
| 177 | SourceLocation BPStartLoc, BPEndLoc; |
| 178 | for (unsigned int I = 0; I < Dim; ++I) { |
| 179 | BPStartLoc = RewriteHelper->getLocationUntil(StartLoc, '['); |
| 180 | BPEndLoc = RewriteHelper->getLocationUntil(BPStartLoc, ']'); |
| 181 | |
| 182 | BracketLocPair *LocPair = new BracketLocPair(); |
| 183 | LocPair->first = BPStartLoc; |
| 184 | LocPair->second = BPEndLoc; |
| 185 | BPVec.push_back(LocPair); |
| 186 | StartLoc = BPEndLoc; |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | void ReduceArrayDim::freeBracketLocPairs(BracketLocPairVector &BPVec) |
| 191 | { |
| 192 | for (BracketLocPairVector::iterator I = BPVec.begin(), |
| 193 | E = BPVec.end(); I != E; ++I) { |
| 194 | delete (*I); |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | void ReduceArrayDim::getInitListExprs(InitListExprVector &InitVec, |
| 199 | const InitListExpr *ILE, |
| 200 | unsigned int Dim) |
| 201 | { |
| 202 | unsigned int NumInits = ILE->getNumInits(); |
| 203 | for (unsigned int I = 0; I < NumInits; ++I) { |
| 204 | const Expr *E = ILE->getInit(I); |
| 205 | const InitListExpr *SubILE = dyn_cast<InitListExpr>(E); |
| 206 | if (!SubILE) |
| 207 | continue; |
| 208 | |
| 209 | if (Dim == 1) { |
| 210 | InitVec.push_back(SubILE); |
| 211 | } |
| 212 | else { |
| 213 | getInitListExprs(InitVec, SubILE, Dim-1); |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | void ReduceArrayDim::rewriteInitListExpr(const InitListExpr *ILE, |
| 219 | unsigned int Dim) |
| 220 | { |
| 221 | TransAssert((Dim > 1) && "Invalid array dimension!"); |
| 222 | InitListExprVector InitVec; |
| 223 | getInitListExprs(InitVec, ILE, Dim-1); |
| 224 | |
| 225 | for (InitListExprVector::reverse_iterator I = InitVec.rbegin(), |
| 226 | E = InitVec.rend(); I != E; ++I) { |
| 227 | SourceLocation RBLoc = (*I)->getRBraceLoc(); |
| 228 | SourceLocation RLLoc = (*I)->getLBraceLoc(); |
| 229 | |
| 230 | const char *RBBuf = SrcManager->getCharacterData(RBLoc); |
| 231 | const char *RLBuf = SrcManager->getCharacterData(RLLoc); |
| 232 | |
| 233 | // make sure RBBuf and RLBuf are correct. They could be incorrect |
| 234 | // for cases like: int a[2][2] = {1} |
| 235 | if (((*RBBuf) == '}') && ((*RLBuf) == '{')) { |
| 236 | TheRewriter.RemoveText(RBLoc, 1); |
| 237 | TheRewriter.RemoveText(RLLoc, 1); |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | unsigned ReduceArrayDim::getArraySize(const ArrayType *ATy) |
| 243 | { |
| 244 | if (const ConstantArrayType *CstArrayTy = |
| 245 | dyn_cast<ConstantArrayType>(ATy)) { |
| 246 | return getConstArraySize(CstArrayTy); |
| 247 | } |
| 248 | |
| 249 | return 1; |
| 250 | } |
| 251 | |
| 252 | void ReduceArrayDim::rewriteOneVarDecl(const VarDecl *VD) |
| 253 | { |
| 254 | const Type *Ty = VD->getType().getTypePtr(); |
| 255 | const ArrayType *ArrayTy = dyn_cast<ArrayType>(Ty); |
| 256 | TransAssert(ArrayTy && "Invalid ArrayType!"); |
| 257 | |
| 258 | ArraySubTypeVector TyVec; |
| 259 | unsigned int Dim = getArrayDimensionAndTypes(ArrayTy, TyVec); |
| 260 | if (VD->hasInit()) { |
| 261 | const Expr *InitE = VD->getInit(); |
| 262 | const InitListExpr *ILE = dyn_cast<InitListExpr>(InitE); |
| 263 | if (ILE) |
| 264 | rewriteInitListExpr(ILE, Dim); |
| 265 | } |
| 266 | |
| 267 | BracketLocPairVector BPVector; |
| 268 | getBracketLocPairs(VD, Dim, BPVector); |
| 269 | TransAssert((BPVector.size() > 1) && "Invalid Bracket Pairs!"); |
| 270 | |
| 271 | ArraySubTypeVector::const_reverse_iterator TyIdx = TyVec.rbegin(); |
| 272 | unsigned LastSz = getArraySize(*TyIdx); |
| 273 | |
| 274 | ++TyIdx; |
| 275 | const ArrayType *SecArrayTy = (*TyIdx); |
| 276 | |
| 277 | BracketLocPairVector::reverse_iterator BIdx = BPVector.rbegin(); |
| 278 | BracketLocPair *LastBracketPair = (*BIdx); |
| 279 | TheRewriter.RemoveText(SourceRange(LastBracketPair->first, |
| 280 | LastBracketPair->second)); |
| 281 | |
| 282 | ++BIdx; |
| 283 | BracketLocPair *SecBracketPair = (*BIdx); |
| 284 | // We keep incomplete array |
| 285 | if (!dyn_cast<IncompleteArrayType>(SecArrayTy)) { |
| 286 | // Keep this value, which is needed for rewriting ArraySubscriptExpr |
| 287 | ArraySz = getArraySize(SecArrayTy); |
| 288 | |
| 289 | std::stringstream TmpSS; |
| 290 | TmpSS << (LastSz * ArraySz); |
| 291 | |
| 292 | SourceLocation StartLoc = (SecBracketPair->first).getLocWithOffset(1); |
| 293 | SourceLocation EndLoc = (SecBracketPair->second).getLocWithOffset(-1); |
| 294 | TheRewriter.ReplaceText(SourceRange(StartLoc, EndLoc), TmpSS.str()); |
| 295 | } |
| 296 | |
| 297 | freeBracketLocPairs(BPVector); |
| 298 | Rewritten = true; |
| 299 | return; |
| 300 | } |
| 301 | |
| 302 | bool ReduceArrayDim::isIntegerExpr(const Expr *Exp) |
| 303 | { |
| 304 | const Expr *E = Exp->IgnoreParenCasts(); |
| 305 | |
| 306 | switch(E->getStmtClass()) { |
| 307 | case Expr::IntegerLiteralClass: |
| 308 | case Expr::CharacterLiteralClass: // Fall-through |
| 309 | return true; |
| 310 | |
| 311 | default: |
| 312 | return false; |
| 313 | } |
| 314 | TransAssert(0 && "Unreachable code!"); |
| 315 | return false; |
| 316 | } |
| 317 | |
| 318 | void ReduceArrayDim::rewriteSubscriptExpr(const ExprVector &IdxExprs) |
| 319 | { |
| 320 | ExprVector::const_iterator I = IdxExprs.begin(); |
| 321 | const Expr *LastE = (*I); |
| 322 | ++I; |
| 323 | const Expr *SecE = (*I); |
| 324 | RewriteHelper->removeArraySubscriptExpr(LastE); |
| 325 | |
| 326 | int LastIdx = -1; |
| 327 | int SecIdx = -1; |
| 328 | if (isIntegerExpr(LastE)) |
| 329 | LastIdx = getIndexAsInteger(LastE); |
| 330 | |
| 331 | if (isIntegerExpr(SecE)) |
| 332 | SecIdx = getIndexAsInteger(SecE); |
| 333 | |
| 334 | if ((LastIdx >= 0) && (SecIdx >= 0)) { |
| 335 | int NewIdx = (SecIdx * ArraySz + LastIdx); |
| 336 | std::stringstream TmpSS; |
| 337 | TmpSS << NewIdx; |
| 338 | RewriteHelper->replaceExpr(SecE, TmpSS.str()); |
| 339 | return; |
| 340 | } |
| 341 | |
| 342 | std::string LastStr, SecStr, newStr; |
| 343 | RewriteHelper->getExprString(LastE, LastStr); |
| 344 | RewriteHelper->getExprString(SecE, SecStr); |
| 345 | std::stringstream TmpSS; |
| 346 | if (ArraySz == 1) { |
| 347 | TmpSS << SecStr << "+" << LastStr; |
| 348 | } |
| 349 | else if (SecIdx == 1) { |
| 350 | TmpSS << ArraySz << "+" << LastStr; |
| 351 | } |
| 352 | else { |
| 353 | TmpSS << "(" << SecStr << ")*" << ArraySz << "+" << LastStr; |
| 354 | } |
| 355 | RewriteHelper->replaceExpr(SecE, TmpSS.str()); |
| 356 | } |
| 357 | |
| 358 | void ReduceArrayDim::handleOneArraySubscriptExpr( |
| 359 | const ArraySubscriptExpr *ASE) |
| 360 | { |
| 361 | const Type *ASETy = ASE->getType().getTypePtr(); |
| 362 | if (!ASETy->isScalarType() && !ASETy->isStructureType() && |
| 363 | !ASETy->isUnionType()) |
| 364 | return; |
| 365 | |
| 366 | ExprVector IdxExprs; |
| 367 | const Expr *BaseE = getBaseExprAndIdxExprs(ASE, IdxExprs); |
| 368 | TransAssert(BaseE && "Empty Base expression!"); |
| 369 | |
| 370 | if (IdxExprs.size() <= 1) |
| 371 | return; |
| 372 | |
| 373 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseE); |
| 374 | if (!DRE) |
| 375 | return; |
| 376 | |
| 377 | const ValueDecl *OrigDecl = DRE->getDecl(); |
| 378 | const VarDecl *VD = dyn_cast<VarDecl>(OrigDecl); |
| 379 | if (!VD) |
| 380 | return; |
| 381 | |
| 382 | const VarDecl *CanonicalVD = VD->getCanonicalDecl(); |
| 383 | if (CanonicalVD != TheVarDecl) |
| 384 | return; |
| 385 | |
| 386 | rewriteSubscriptExpr(IdxExprs); |
| 387 | Rewritten = true; |
| 388 | } |
| 389 | |
| 390 | ReduceArrayDim::~ReduceArrayDim(void) |
| 391 | { |
| 392 | delete CollectionVisitor; |
| 393 | delete RewriteVisitor; |
| 394 | } |
| 395 |