Debian Codegraph @

clang_delta/ExpressionDetector.cpp

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 //===----------------------------------------------------------------------===//
2 //
3 // Copyright (c) 2016, 2017, 2018, 2019 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 "ExpressionDetector.h"
16
17 #include "clang/AST/RecursiveASTVisitor.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Lex/Preprocessor.h"
21
22 #include "CommonStatementVisitor.h"
23 #include "TransformationManager.h"
24
25 using namespace clang;
26
27 static const char *DescriptionMsg =
28 "Insert a printf statement to print out the value of an expression. \
29 Currently, only expressions of type integer and floating point are \
30 considered valid. The transformation also injects a static control \
31 variable to ensure that the expression of interest will be printed \
32 only once.\n";
33
34 // Some known issues:
35 // (1) Because we don't have any array-bound analysis, this pass will
36 // turn the following code into one that would coredump:
37 // if (argc == 2 && !strcmp(argv[1], "xxx"))
38 // ==>
39 // int __creduce_expr_tmp_xxx = !strcmp(argv[1], "xxx");
40 // ...
41 // (2) we don't perform pointer analysis, the transformed program
42 // will produce different result from the original one, e.g.,
43 // int *x = &g;
44 // foo((*x) += 1 || g);
45 // ==>
46 // int *x = &g;
47 // int __creduce_expr_tmp_xxx = g;
48 // ...
49 // foo((*x) += 1 || __creduce_expr_tmp_xxx);
50
51 static RegisterTransformation<ExpressionDetector>
52 Trans("expression-detector", DescriptionMsg);
53
54 namespace {
55 class IncludesPPCallbacks : public PPCallbacks {
56 public:
57 IncludesPPCallbacks(SourceManager &M, const std::string &Name,
58 bool &H, SourceLocation &Loc)
59 : SrcManager(M), HeaderName(Name), HasHeader(H), HeaderLoc(Loc)
60 { }
61
62 virtual void InclusionDirective(SourceLocation HashLoc,
63 const Token &IncludeTok,
64 StringRef FileName, bool IsAngled,
65 CharSourceRange FilenameRange, OptionalFileEntryRef File,
66 StringRef SearchPath, StringRef RelativePath,
67 const Module *Imported,
68 SrcMgr::CharacteristicKind FileType) override;
69
70 private:
71 SourceManager &SrcManager;
72
73 const std::string &HeaderName;
74
75 bool &HasHeader;
76
77 SourceLocation &HeaderLoc;
78 };
79
80 void IncludesPPCallbacks::InclusionDirective(SourceLocation HashLoc,
81 const Token &/*IncludeTok*/,
82 StringRef FileName,
83 bool /*IsAngled*/,
84 CharSourceRange /*FilenameRange*/,
85 OptionalFileEntryRef /*File*/,
86 StringRef /*SearchPath*/,
87 StringRef /*RelativePath*/,
88 const Module * /*Imported*/,
89 SrcMgr::CharacteristicKind /*FileType*/)
90 {
91 if (!SrcManager.isInMainFile(HashLoc))
92 return;
93 // We may have multiple "#include <stdio.h>". Only handle the first one.
94 if (!HasHeader && FileName == HeaderName) {
95 HasHeader = true;
96 HeaderLoc = HashLoc;
97 }
98 }
99
100 // Collecting all tmp vars __creduce_expr_tmp_xxx within a statement
101 // generated by C-Reduce
102 class LocalTmpVarCollector : public RecursiveASTVisitor<LocalTmpVarCollector> {
103 public:
104 LocalTmpVarCollector(SmallVector<const VarDecl *, 4> &V, const std::string &P)
105 : TmpVars(V), Prefix(P)
106 { }
107
108 bool VisitDeclRefExpr(DeclRefExpr *DRE);
109
110 private:
111 SmallVector<const VarDecl *, 4> &TmpVars;
112
113 const std::string &Prefix;
114 };
115
116 bool LocalTmpVarCollector::VisitDeclRefExpr(DeclRefExpr *DRE)
117 {
118 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
119 if (!VD)
120 return true;
121 if (VD->getName().startswith(Prefix))
122 TmpVars.push_back(VD);
123 return true;
124 }
125
126 // For a given statement, collect all expressions, each of which is
127 // (1) either the sub-expression of an inc, dec or addrof operator; or
128 // (2) the LHS of a binary operator;
129 class LocalUOBOVisitor : public RecursiveASTVisitor<LocalUOBOVisitor> {
130 public:
131 explicit LocalUOBOVisitor(llvm::SmallPtrSet<const Expr *, 10> &ES)
132 : InvalidExprs(ES)
133 { }
134
135 bool VisitUnaryOperator(UnaryOperator *UO);
136
137 bool VisitBinaryOperator(BinaryOperator *BO);
138
139 private:
140 llvm::SmallPtrSet<const Expr *, 10> &InvalidExprs;
141 };
142
143 bool LocalUOBOVisitor::VisitUnaryOperator(UnaryOperator *UO)
144 {
145 if (!UO->isIncrementDecrementOp() && UO->getOpcode() != UO_AddrOf)
146 return true;
147
148 const Expr *E = UO->getSubExpr();
149 InvalidExprs.insert(E->IgnoreParenImpCasts());
150 return true;
151 }
152
153 bool LocalUOBOVisitor::VisitBinaryOperator(BinaryOperator *BO)
154 {
155 if (!BO->isAssignmentOp())
156 return true;
157 const Expr *E = BO->getLHS();
158 InvalidExprs.insert(E->IgnoreParenImpCasts());
159 return true;
160 }
161
162 } // End anonymous namespace
163
164 class ExprDetectorTempVarVisitor :
165 public RecursiveASTVisitor<ExprDetectorTempVarVisitor> {
166 public:
167
168 explicit ExprDetectorTempVarVisitor(ExpressionDetector *Instance)
169 : ConsumerInstance(Instance)
170 { }
171
172 bool VisitDeclStmt(DeclStmt *DS);
173
174 private:
175
176 ExpressionDetector *ConsumerInstance;
177 };
178
179 bool ExprDetectorTempVarVisitor::VisitDeclStmt(DeclStmt *DS)
180 {
181 for (auto I : DS->decls()) {
182 ConsumerInstance->addOneTempVar(dyn_cast<VarDecl>(I));
183 }
184 return true;
185 }
186
187 class ExprDetectorCollectionVisitor :
188 public RecursiveASTVisitor<ExprDetectorCollectionVisitor> {
189 public:
190
191 explicit ExprDetectorCollectionVisitor(ExpressionDetector *Instance)
192 : ConsumerInstance(Instance)
193 { }
194
195 bool VisitFunctionDecl(FunctionDecl *FD);
196
197 private:
198
199 ExpressionDetector *ConsumerInstance;
200 };
201
202 class ExprDetectorStmtVisitor :
203 public CommonStatementVisitor<ExprDetectorStmtVisitor> {
204 public:
205
206 explicit ExprDetectorStmtVisitor(ExpressionDetector *Instance)
207 : ConsumerInstance(Instance)
208 { }
209
210 bool VisitExpr(Expr *E);
211
212 private:
213 ExpressionDetector *ConsumerInstance;
214 };
215
216 bool ExprDetectorCollectionVisitor::VisitFunctionDecl(FunctionDecl *FD)
217 {
218 if (!ConsumerInstance->HFInfo.HasFunction &&
219 FD->getNameAsString() == ConsumerInstance->HFInfo.FunctionName) {
220 ConsumerInstance->HFInfo.HasFunction = true;
221 ConsumerInstance->HFInfo.FunctionLoc = FD->getSourceRange().getBegin();
222 }
223
224 if (ConsumerInstance->isInIncludedFile(FD) ||
225 !FD->isThisDeclarationADefinition())
226 return true;
227
228 ExprDetectorTempVarVisitor VarVisitor(ConsumerInstance);
229 VarVisitor.TraverseDecl(FD);
230
231 ExprDetectorStmtVisitor StmtVisitor(ConsumerInstance);
232 StmtVisitor.setCurrentFunctionDecl(FD);
233 StmtVisitor.TraverseDecl(FD);
234 StmtVisitor.setCurrentFunctionDecl(NULL);
235 ConsumerInstance->UniqueExprs.clear();
236 ConsumerInstance->ProcessedExprs.clear();
237 return true;
238 }
239
240 bool ExprDetectorStmtVisitor::VisitExpr(Expr *E)
241 {
242 if (ConsumerInstance->isInIncludedFile(E))
243 return true;
244
245 switch(E->getStmtClass()) {
246 default: return true;
247
248 case Expr::ArraySubscriptExprClass:
249 case Expr::BinaryOperatorClass:
250 case Expr::CallExprClass:
251 case Expr::DeclRefExprClass:
252 case Expr::MemberExprClass:
253 case Expr::UnaryOperatorClass: // Fall-through
254 break;
255 }
256
257 const Type *Ty = E->getType().getTypePtr();
258 // Currently, integer and floating point only.
259 if (!Ty->isIntegerType() && !Ty->isFloatingType())
260 return true;
261
262 if (!ConsumerInstance->isValidExpr(CurrentStmt, E))
263 return true;
264
265 ConsumerInstance->ValidInstanceNum++;
266 if (ConsumerInstance->ValidInstanceNum ==
267 ConsumerInstance->TransformationCounter) {
268 ConsumerInstance->TheFunc = CurrentFuncDecl;
269 ConsumerInstance->TheStmt = CurrentStmt;
270 ConsumerInstance->TheExpr = E;
271 }
272 return true;
273 }
274
275 void ExpressionDetector::Initialize(ASTContext &context)
276 {
277 Transformation::Initialize(context);
278 CollectionVisitor = new ExprDetectorCollectionVisitor(this);
279 if (CheckReference) {
280 ControlVarNamePrefix = CheckedVarNamePrefix;
281 HFInfo.HeaderName = "stdlib.h";
282 HFInfo.FunctionName = "abort";
283 HFInfo.FunctionDeclStr = "void abort(void)";
284 }
285 else {
286 ControlVarNamePrefix = PrintedVarNamePrefix;
287 HFInfo.HeaderName = "stdio.h";
288 HFInfo.FunctionName = "printf";
289 HFInfo.FunctionDeclStr = "int printf(const char *format, ...)";
290 }
291
292 ControlVarNameQueryWrap =
293 new TransNameQueryWrap(ControlVarNamePrefix);
294 TmpVarNameQueryWrap =
295 new TransNameQueryWrap(TmpVarNamePrefix);
296 Preprocessor &PP = TransformationManager::getPreprocessor();
297 IncludesPPCallbacks *C =
298 new IncludesPPCallbacks(PP.getSourceManager(),
299 HFInfo.HeaderName,
300 HFInfo.HasHeader,
301 HFInfo.HeaderLoc);
302 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(C));
303 }
304
305 bool ExpressionDetector::HandleTopLevelDecl(DeclGroupRef D)
306 {
307 // Skip C++ programs for now.
308 if (TransformationManager::isCXXLangOpt()) {
309 ValidInstanceNum = 0;
310 return true;
311 }
312
313 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
314 CollectionVisitor->TraverseDecl(*I);
315 }
316 return true;
317 }
318
319 void ExpressionDetector::HandleTranslationUnit(ASTContext &Ctx)
320 {
321 if (QueryInstanceOnly)
322 return;
323
324 if (TransformationCounter > ValidInstanceNum) {
325 TransError = TransMaxInstanceError;
326 return;
327 }
328
329 Ctx.getDiagnostics().setSuppressAllDiagnostics(false);
330
331 TransAssert(TheFunc && "NULL TheFunc!");
332 TransAssert(TheStmt && "NULL TheStmt!");
333 TransAssert(TheExpr && "NULL TheExpr");
334
335 if (DoReplacement) {
336 RewriteHelper->replaceExpr(TheExpr, Replacement);
337 }
338 else {
339 ControlVarNameQueryWrap->TraverseDecl(TheFunc);
340 TmpVarNameQueryWrap->TraverseDecl(TheFunc);
341 doRewrite();
342 }
343
344 if (Ctx.getDiagnostics().hasErrorOccurred() ||
345 Ctx.getDiagnostics().hasFatalErrorOccurred())
346 TransError = TransInternalError;
347 }
348
349 // Return true if
350 // (1) we don't have the function declaration or the decl appears after
351 // the recorded FunctionLoc; and
352 // (2) header file is not included in the main file or header file
353 // appears after the Loc.
354 bool ExpressionDetector::shouldAddFunctionDecl(SourceLocation Loc)
355 {
356 return (!HFInfo.HasFunction ||
357 SrcManager->isBeforeInSLocAddrSpace(Loc, HFInfo.FunctionLoc)) &&
358 (!HFInfo.HasHeader ||
359 SrcManager->isBeforeInSLocAddrSpace(Loc, HFInfo.HeaderLoc));
360 }
361
362 void ExpressionDetector::addOneTempVar(const VarDecl *VD)
363 {
364 if (!VD)
365 return;
366 if (!VD->getName().startswith(TmpVarNamePrefix))
367 return;
368 if (const Expr *E = VD->getInit())
369 ProcessedExprs[VD] = E->IgnoreParenImpCasts();
370 }
371
372 bool ExpressionDetector::refToTmpVar(const NamedDecl *ND)
373 {
374 StringRef Name = ND->getName();
375 // We don't want to repeatly replace temporary variables
376 // __creduce_expr_tmp_xxx, __creduce_printed_yy and __creduce_checked_zzz.
377 return Name.startswith(TmpVarNamePrefix) ||
378 Name.startswith(PrintedVarNamePrefix) ||
379 Name.startswith(CheckedVarNamePrefix);
380 }
381
382 // Reference: IdenticalExprChecker.cpp from Clang
383 bool ExpressionDetector::isIdenticalExpr(const Expr *E1, const Expr *E2)
384 {
385 if (!E1 || !E2)
386 return !E1 && !E2;
387
388 E1 = E1->IgnoreParenImpCasts();
389 E2 = E2->IgnoreParenImpCasts();
390 Stmt::StmtClass SC1 = E1->getStmtClass();
391 Stmt::StmtClass SC2 = E2->getStmtClass();
392 if (SC1 != SC2)
393 return false;
394
395 // If either of E1 or E2 has side-effects, treat them as non-identical
396 // expressions.
397 if (E1->HasSideEffects(*Context) || E2->HasSideEffects(*Context))
398 return false;
399
400 Expr::const_child_iterator I1 = E1->child_begin(), I2 = E2->child_begin();
401 while (I1 != E1->child_end() && I2 != E2->child_end()) {
402 if (!isIdenticalExpr(dyn_cast<Expr>(*I1), dyn_cast<Expr>(*I2)))
403 return false;
404 ++I1;
405 ++I2;
406 }
407 if (I1 != E1->child_end() || I2 != E2->child_end())
408 return false;
409
410 switch (SC1) {
411 default:
412 return false;
413 case Stmt::ArraySubscriptExprClass:
414 case Stmt::CallExprClass: // Fall-through
415 return true;
416
417 case Stmt::CStyleCastExprClass: {
418 const CStyleCastExpr *Cast1 = cast<CStyleCastExpr>(E1);
419 const CStyleCastExpr *Cast2 = cast<CStyleCastExpr>(E2);
420 return Cast1->getTypeAsWritten() == Cast2->getTypeAsWritten();
421 }
422
423 case Stmt::MemberExprClass: {
424 const MemberExpr *ME1 = cast<MemberExpr>(E1);
425 const MemberExpr *ME2 = cast<MemberExpr>(E2);
426 return ME1->getMemberDecl() == ME2->getMemberDecl();
427 }
428
429 case Stmt::DeclRefExprClass: {
430 const DeclRefExpr *DRE1 = cast<DeclRefExpr>(E1);
431 const DeclRefExpr *DRE2 = cast<DeclRefExpr>(E2);
432 return DRE1->getDecl() == DRE2->getDecl();
433 }
434
435 case Stmt::CompoundAssignOperatorClass:
436 case Stmt::BinaryOperatorClass: // Fall-through
437 {
438 const BinaryOperator *BO1 = cast<BinaryOperator>(E1);
439 const BinaryOperator *BO2 = cast<BinaryOperator>(E2);
440 return BO1->getOpcode() == BO2->getOpcode();
441 }
442
443 case Stmt::UnaryOperatorClass:
444 {
445 const UnaryOperator *UO1 = cast<UnaryOperator>(E1);
446 const UnaryOperator *UO2 = cast<UnaryOperator>(E2);
447 return UO1->getOpcode() == UO2->getOpcode();
448 }
449
450 case Stmt::CharacterLiteralClass: {
451 const CharacterLiteral *Lit1 = cast<CharacterLiteral>(E1);
452 const CharacterLiteral *Lit2 = cast<CharacterLiteral>(E2);
453 return Lit1->getValue() == Lit2->getValue();
454 }
455
456 case Stmt::StringLiteralClass: {
457 const clang::StringLiteral *Lit1 = cast<clang::StringLiteral>(E1);
458 const clang::StringLiteral *Lit2 = cast<clang::StringLiteral>(E2);
459 return Lit1->getBytes() == Lit2->getBytes();
460 }
461
462 case Stmt::IntegerLiteralClass: {
463 const IntegerLiteral *Lit1 = cast<IntegerLiteral>(E1);
464 const IntegerLiteral *Lit2 = cast<IntegerLiteral>(E2);
465 llvm::APInt I1 = Lit1->getValue();
466 llvm::APInt I2 = Lit2->getValue();
467 return I1.getBitWidth() == I2.getBitWidth() && I1 == I2;
468 }
469
470 case Stmt::FloatingLiteralClass: {
471 const FloatingLiteral *Lit1 = cast<FloatingLiteral>(E1);
472 const FloatingLiteral *Lit2 = cast<FloatingLiteral>(E2);
473 return Lit1->getValue().bitwiseIsEqual(Lit2->getValue());
474 }
475
476 }
477
478 return true;
479 }
480
481 bool ExpressionDetector::hasIdenticalExpr(
482 const SmallVector<const VarDecl *, 4> &TmpVars, const Expr *E)
483 {
484 for (auto V : TmpVars) {
485 auto I = ProcessedExprs.find(V);
486 if (I != ProcessedExprs.end() && isIdenticalExpr(I->second, E))
487 return true;
488 }
489 return false;
490 }
491
492 bool ExpressionDetector::isValidExpr(Stmt *S, const Expr *E)
493 {
494 Stmt::StmtClass SC = S->getStmtClass();
495 // Don't mess up with init/condition/inc exprs of loops.
496 if (SC == Stmt::ForStmtClass ||
497 SC == Stmt::DoStmtClass ||
498 SC == Stmt::WhileStmtClass) {
499 return false;
500 }
501
502 if (const Expr *SE = dyn_cast<Expr>(S)) {
503 // Don't do self-replacement. Note that E can't be of paren
504 // or cast expr (See ExprDetectorStmtVisitor::VisitExpr).
505 if (SE->IgnoreParenCasts() == E)
506 return false;
507 }
508
509 if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
510 if (DS->isSingleDecl()) {
511 const NamedDecl *ND = dyn_cast<NamedDecl>(DS->getSingleDecl());
512 if (ND == NULL || refToTmpVar(ND))
513 return false;
514 }
515 else {
516 // Skip group decls for now.
517 return false;
518 }
519 }
520
521 // don't handle !__creduce_printed and !__creduce_checked
522 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
523 if (UO->getOpcode() == UO_LNot) {
524 if (const DeclRefExpr *SubE =
525 dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParenCasts())) {
526 StringRef SubEName = SubE->getDecl()->getName();
527 if (SubEName.startswith(PrintedVarNamePrefix) ||
528 SubEName.startswith(CheckedVarNamePrefix))
529 return false;
530 }
531 }
532 }
533
534 // skip if (__creduce_expr_tmp != xxx)
535 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
536 if (BO->getOpcode() == BO_NE) {
537 const Expr *Lhs = BO->getLHS()->IgnoreParenCasts();
538 const Expr *Rhs = BO->getRHS()->IgnoreParenCasts();
539 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Lhs);
540 Stmt::StmtClass SC = Rhs->getStmtClass();
541 bool IsLit = SC == Stmt::IntegerLiteralClass ||
542 SC == Stmt::FloatingLiteralClass;
543 if (IsLit && DRE &&
544 DRE->getDecl()->getName().startswith(TmpVarNamePrefix) &&
545 S->getStmtClass() == Stmt::IfStmtClass) {
546 return false;
547 }
548 }
549 }
550
551 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
552 // Don't repeatly process temp vars.
553 if (refToTmpVar(DRE->getDecl()))
554 return false;
555 // Skip cases such as printf("%d", a);
556 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
557 const FunctionDecl *FD = CE->getDirectCallee();
558 if (FD && FD->getNameAsString() == "printf")
559 return false;
560 }
561 }
562
563 // If the Expr is the LHS of a binary operator, we don't
564 // need to process it, e.g., given
565 // a = x + y;
566 // we don't need to replace "a" with "__creduce_expr_tmp_xxx"
567 //
568 // We also skip x++, --x and &x, because we don't want to make
569 // the following transformation:
570 // x++;
571 // ==>
572 // __creduce_expr_tmp_xxx = x;
573 // ++__creduce_expr_tmp_xxx;
574 // In the original code, we pre-increment x, but after the "transformation",
575 // we would end up doing that for __creduce_expr_tmp_xxx.
576 // Note that we cache the result, because we don't want to re-visit the same
577 // statement many times. Gain a log of performance improvement.
578 auto EI = InvalidExprsInUOBO.find(S);
579 if (EI == InvalidExprsInUOBO.end()) {
580 llvm::SmallPtrSet<const Expr *, 10> InvalidExprs;
581 LocalUOBOVisitor UOBOVisitor(InvalidExprs);
582 UOBOVisitor.TraverseStmt(S);
583 InvalidExprsInUOBO[S] = InvalidExprs;
584 if (InvalidExprs.count(E))
585 return false;
586 }
587 else if (EI->second.count(E)) {
588 return false;
589 }
590
591 // Skip identical expression. For example, for
592 // the given statement below:
593 // x = y[1] + y[1] + y[1];
594 // we only need to print one y[1] before the assignment statement.
595 // This optimization is able to avoid a lots of dups.
596 auto &Vec = UniqueExprs[S];
597 for (auto I : Vec) {
598 if (isIdenticalExpr(I, E))
599 return false;
600 }
601 // update UniqueExprs
602 Vec.push_back(E);
603
604 // The optimization above only works for single iteration. The code
605 // below handles the following patterns:
606 // int __creduce_expr_tmp_1 = y[1];
607 // ...printf("%d\n", __creduce_expr_tmp_1);
608 // x = __creduce_expr_tmp_1 + y[1] + y[1]
609 // We don't need to generate another tmp var for y[1] in this case.
610 auto VI = TmpVarsInStmt.find(S);
611 if (VI == TmpVarsInStmt.end()) {
612 SmallVector<const VarDecl *, 4> TmpVars;
613 LocalTmpVarCollector TmpCollector(TmpVars, TmpVarNamePrefix);
614 TmpCollector.TraverseStmt(S);
615 TmpVarsInStmt[S] = TmpVars;
616 if (hasIdenticalExpr(TmpVars, E))
617 return false;
618 }
619 else if (hasIdenticalExpr(VI->second, E)) {
620 return false;
621 }
622
623 return true;
624 }
625
626 static std::string getFormatString(const BuiltinType *BT)
627 {
628 switch(BT->getKind()) {
629 default:
630 TransAssert(0 && "Bad BuiltinType!");
631 return "";
632
633 case BuiltinType::Bool:
634 case BuiltinType::Char_U:
635 case BuiltinType::WChar_U:
636 case BuiltinType::UChar:
637 case BuiltinType::UShort:
638 case BuiltinType::UInt:
639 return "u";
640
641 case BuiltinType::Char_S:
642 case BuiltinType::SChar:
643 case BuiltinType::WChar_S:
644 case BuiltinType::Short:
645 case BuiltinType::Int:
646 case BuiltinType::Char16:
647 case BuiltinType::Char32:
648 return "d";
649
650 case BuiltinType::ULong:
651 return "lu";
652
653 case BuiltinType::Long:
654 return "ld";
655
656 case BuiltinType::ULongLong:
657 return "llu";
658
659 case BuiltinType::LongLong:
660 return "lld";
661
662 case BuiltinType::Float:
663 case BuiltinType::Double:
664 return "f";
665
666 case BuiltinType::LongDouble:
667 return "Lf";
668 }
669
670 return "";
671 }
672
673 void ExpressionDetector::doRewrite()
674 {
675 SourceLocation LocStart = TheStmt->getBeginLoc();
676 if (shouldAddFunctionDecl(LocStart)) {
677 SourceLocation Loc =
678 SrcManager->getLocForStartOfFile(SrcManager->getMainFileID());
679 TheRewriter.InsertText(Loc, HFInfo.FunctionDeclStr+";\n");
680 }
681
682 std::string Str, ExprStr, TmpVarName;
683 RewriteHelper->getExprString(TheExpr, ExprStr);
684
685 std::string TyStr;
686 TheExpr->getType().getAsStringInternal(TyStr, Context->getPrintingPolicy());
687 TmpVarName = TmpVarNamePrefix +
688 std::to_string(TmpVarNameQueryWrap->getMaxNamePostfix()+1);
689 Str += TyStr + " " + TmpVarName + " = " + ExprStr + ";\n";
690
691 std::string ControlVarName = ControlVarNamePrefix +
692 std::to_string(ControlVarNameQueryWrap->getMaxNamePostfix()+1);
693 Str += "static int " + ControlVarName + " = 0;\n";
694 Str += "if (" + ControlVarName + " == __CREDUCE_INSTANCE_NUMBER) {\n";
695 if (CheckReference) {
696 Str += " if (" + TmpVarName + " != " + ReferenceValue + ") ";
697 Str += HFInfo.FunctionName + "();\n";
698 }
699 else {
700 const Type *Ty =
701 TheExpr->getType().getTypePtr()->getUnqualifiedDesugaredType();
702 std::string FormatStr = getFormatString(dyn_cast<BuiltinType>(Ty));
703 Str += " " + HFInfo.FunctionName;
704 Str += "(\"creduce_value(%" + FormatStr + ")\\n\", ";
705 Str += TmpVarName + ");\n";
706 }
707 Str += "}\n";
708 Str += "++" + ControlVarName + ";";
709
710 bool NeedParen = TheStmt->getStmtClass() != Stmt::DeclStmtClass;
711 RewriteHelper->addStringBeforeStmtAndReplaceExpr(TheStmt, Str,
712 TheExpr, TmpVarName,
713 NeedParen);
714 }
715
716 ExpressionDetector::~ExpressionDetector(void)
717 {
718 delete CollectionVisitor;
719 delete ControlVarNameQueryWrap;
720 delete TmpVarNameQueryWrap;
721 }