1 //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // "Meta" ASTConsumer for running different source analyses.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #define DEBUG_TYPE "AnalysisConsumer"
15 
16 #include "AnalysisConsumer.h"
17 #include "clang/AST/ASTConsumer.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ParentMap.h"
22 #include "clang/AST/RecursiveASTVisitor.h"
23 #include "clang/Analysis/CFG.h"
24 #include "clang/Analysis/CallGraph.h"
25 #include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
26 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
27 #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
28 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
30 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
31 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
32 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
33 
34 #include "clang/Basic/FileManager.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Frontend/AnalyzerOptions.h"
37 #include "clang/Lex/Preprocessor.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Program.h"
41 #include "llvm/Support/Timer.h"
42 #include "llvm/ADT/DepthFirstIterator.h"
43 #include "llvm/ADT/OwningPtr.h"
44 #include "llvm/ADT/Statistic.h"
45 
46 #include <queue>
47 
48 using namespace clang;
49 using namespace ento;
50 using llvm::SmallPtrSet;
51 
52 static ExplodedNode::Auditor* CreateUbiViz();
53 
54 STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
55 STATISTIC(NumFunctionsAnalyzed, "The # of functions analysed (as top level).");
56 STATISTIC(NumBlocksInAnalyzedFunctions,
57                      "The # of basic blocks in the analyzed functions.");
58 STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
59 
60 //===----------------------------------------------------------------------===//
61 // Special PathDiagnosticConsumers.
62 //===----------------------------------------------------------------------===//
63 
64 static PathDiagnosticConsumer*
65 createPlistHTMLDiagnosticConsumer(const std::string& prefix,
66                                 const Preprocessor &PP) {
67   PathDiagnosticConsumer *PD =
68     createHTMLDiagnosticConsumer(llvm::sys::path::parent_path(prefix), PP);
69   return createPlistDiagnosticConsumer(prefix, PP, PD);
70 }
71 
72 //===----------------------------------------------------------------------===//
73 // AnalysisConsumer declaration.
74 //===----------------------------------------------------------------------===//
75 
76 namespace {
77 
78 class AnalysisConsumer : public ASTConsumer,
79                          public RecursiveASTVisitor<AnalysisConsumer> {
80   enum AnalysisMode {
81     ANALYSIS_SYNTAX,
82     ANALYSIS_PATH,
83     ANALYSIS_ALL
84   };
85 
86   /// Mode of the analyzes while recursively visiting Decls.
87   AnalysisMode RecVisitorMode;
88   /// Bug Reporter to use while recursively visiting Decls.
89   BugReporter *RecVisitorBR;
90 
91 public:
92   ASTContext *Ctx;
93   const Preprocessor &PP;
94   const std::string OutDir;
95   AnalyzerOptions Opts;
96   ArrayRef<std::string> Plugins;
97 
98   // PD is owned by AnalysisManager.
99   PathDiagnosticConsumer *PD;
100 
101   StoreManagerCreator CreateStoreMgr;
102   ConstraintManagerCreator CreateConstraintMgr;
103 
104   OwningPtr<CheckerManager> checkerMgr;
105   OwningPtr<AnalysisManager> Mgr;
106 
107   /// Time the analyzes time of each translation unit.
108   static llvm::Timer* TUTotalTimer;
109 
110   /// The information about analyzed functions shared throughout the
111   /// translation unit.
112   FunctionSummariesTy FunctionSummaries;
113 
114   AnalysisConsumer(const Preprocessor& pp,
115                    const std::string& outdir,
116                    const AnalyzerOptions& opts,
117                    ArrayRef<std::string> plugins)
118     : RecVisitorMode(ANALYSIS_ALL), RecVisitorBR(0),
119       Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins), PD(0) {
120     DigestAnalyzerOptions();
121     if (Opts.PrintStats) {
122       llvm::EnableStatistics();
123       TUTotalTimer = new llvm::Timer("Analyzer Total Time");
124     }
125   }
126 
127   ~AnalysisConsumer() {
128     if (Opts.PrintStats)
129       delete TUTotalTimer;
130   }
131 
132   void DigestAnalyzerOptions() {
133     // Create the PathDiagnosticConsumer.
134     if (!OutDir.empty()) {
135       switch (Opts.AnalysisDiagOpt) {
136       default:
137 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \
138         case PD_##NAME: PD = CREATEFN(OutDir, PP); break;
139 #include "clang/Frontend/Analyses.def"
140       }
141     } else if (Opts.AnalysisDiagOpt == PD_TEXT) {
142       // Create the text client even without a specified output file since
143       // it just uses diagnostic notes.
144       PD = createTextPathDiagnosticConsumer("", PP);
145     }
146 
147     // Create the analyzer component creators.
148     switch (Opts.AnalysisStoreOpt) {
149     default:
150       llvm_unreachable("Unknown store manager.");
151 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN)           \
152       case NAME##Model: CreateStoreMgr = CREATEFN; break;
153 #include "clang/Frontend/Analyses.def"
154     }
155 
156     switch (Opts.AnalysisConstraintsOpt) {
157     default:
158       llvm_unreachable("Unknown store manager.");
159 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN)     \
160       case NAME##Model: CreateConstraintMgr = CREATEFN; break;
161 #include "clang/Frontend/Analyses.def"
162     }
163   }
164 
165   void DisplayFunction(const Decl *D, AnalysisMode Mode) {
166     if (!Opts.AnalyzerDisplayProgress)
167       return;
168 
169     SourceManager &SM = Mgr->getASTContext().getSourceManager();
170     PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
171     if (Loc.isValid()) {
172       llvm::errs() << "ANALYZE";
173       switch (Mode) {
174         case ANALYSIS_SYNTAX: llvm::errs() << "(Syntax)"; break;
175         case ANALYSIS_PATH: llvm::errs() << "(Path Sensitive)"; break;
176         case ANALYSIS_ALL: break;
177       };
178       llvm::errs() << ": " << Loc.getFilename();
179       if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
180         const NamedDecl *ND = cast<NamedDecl>(D);
181         llvm::errs() << ' ' << *ND << '\n';
182       }
183       else if (isa<BlockDecl>(D)) {
184         llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
185                      << Loc.getColumn() << '\n';
186       }
187       else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
188         Selector S = MD->getSelector();
189         llvm::errs() << ' ' << S.getAsString();
190       }
191     }
192   }
193 
194   virtual void Initialize(ASTContext &Context) {
195     Ctx = &Context;
196     checkerMgr.reset(createCheckerManager(Opts, PP.getLangOpts(), Plugins,
197                                           PP.getDiagnostics()));
198     Mgr.reset(new AnalysisManager(*Ctx, PP.getDiagnostics(),
199                                   PP.getLangOpts(), PD,
200                                   CreateStoreMgr, CreateConstraintMgr,
201                                   checkerMgr.get(),
202                                   /* Indexer */ 0,
203                                   Opts.MaxNodes, Opts.MaxLoop,
204                                   Opts.VisualizeEGDot, Opts.VisualizeEGUbi,
205                                   Opts.AnalysisPurgeOpt, Opts.EagerlyAssume,
206                                   Opts.TrimGraph,
207                                   Opts.UnoptimizedCFG, Opts.CFGAddImplicitDtors,
208                                   Opts.CFGAddInitializers,
209                                   Opts.EagerlyTrimEGraph,
210                                   Opts.IPAMode,
211                                   Opts.InlineMaxStackDepth,
212                                   Opts.InlineMaxFunctionSize,
213                                   Opts.InliningMode,
214                                   Opts.NoRetryExhausted));
215   }
216 
217   virtual void HandleTranslationUnit(ASTContext &C);
218 
219   /// \brief Build the call graph for the TU and use it to define the order
220   /// in which the functions should be visited.
221   void HandleDeclsGallGraph(TranslationUnitDecl *TU);
222 
223   /// \brief Run analyzes(syntax or path sensitive) on the given function.
224   /// \param Mode - determines if we are requesting syntax only or path
225   /// sensitive only analysis.
226   /// \param VisitedCallees - The output parameter, which is populated with the
227   /// set of functions which should be considered analyzed after analyzing the
228   /// given root function.
229   void HandleCode(Decl *D, AnalysisMode Mode, SetOfDecls *VisitedCallees = 0);
230 
231   /// \brief Check if we should skip (not analyze) the given function.
232   bool skipFunction(Decl *D);
233 
234   void RunPathSensitiveChecks(Decl *D, SetOfDecls *VisitedCallees);
235   void ActionExprEngine(Decl *D, bool ObjCGCEnabled, SetOfDecls *VisitedCallees);
236 
237   /// Visitors for the RecursiveASTVisitor.
238 
239   /// Handle callbacks for arbitrary Decls.
240   bool VisitDecl(Decl *D) {
241     checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
242     return true;
243   }
244 
245   bool VisitFunctionDecl(FunctionDecl *FD) {
246     IdentifierInfo *II = FD->getIdentifier();
247     if (II && II->getName().startswith("__inline"))
248       return true;
249 
250     // We skip function template definitions, as their semantics is
251     // only determined when they are instantiated.
252     if (FD->isThisDeclarationADefinition() &&
253         !FD->isDependentContext()) {
254       HandleCode(FD, RecVisitorMode);
255     }
256     return true;
257   }
258 
259   bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
260     checkerMgr->runCheckersOnASTDecl(MD, *Mgr, *RecVisitorBR);
261     if (MD->isThisDeclarationADefinition())
262       HandleCode(MD, RecVisitorMode);
263     return true;
264   }
265 };
266 } // end anonymous namespace
267 
268 
269 //===----------------------------------------------------------------------===//
270 // AnalysisConsumer implementation.
271 //===----------------------------------------------------------------------===//
272 llvm::Timer* AnalysisConsumer::TUTotalTimer = 0;
273 
274 void AnalysisConsumer::HandleDeclsGallGraph(TranslationUnitDecl *TU) {
275   // Otherwise, use the Callgraph to derive the order.
276   // Build the Call Graph.
277   CallGraph CG;
278   CG.addToCallGraph(TU);
279 
280   // Find the top level nodes - children of root + the unreachable (parentless)
281   // nodes.
282   llvm::SmallVector<CallGraphNode*, 24> TopLevelFunctions;
283   for (CallGraph::nodes_iterator TI = CG.parentless_begin(),
284                                  TE = CG.parentless_end(); TI != TE; ++TI) {
285     TopLevelFunctions.push_back(*TI);
286     NumFunctionTopLevel++;
287   }
288   CallGraphNode *Entry = CG.getRoot();
289   for (CallGraphNode::iterator I = Entry->begin(),
290                                E = Entry->end(); I != E; ++I) {
291     TopLevelFunctions.push_back(*I);
292     NumFunctionTopLevel++;
293   }
294 
295   // Make sure the nodes are sorted in order reverse of their definition in the
296   // translation unit. This step is very important for performance. It ensures
297   // that we analyze the root functions before the externally available
298   // subroutines.
299   std::queue<CallGraphNode*> BFSQueue;
300   for (llvm::SmallVector<CallGraphNode*, 24>::reverse_iterator
301          TI = TopLevelFunctions.rbegin(), TE = TopLevelFunctions.rend();
302          TI != TE; ++TI)
303     BFSQueue.push(*TI);
304 
305   // BFS over all of the functions, while skipping the ones inlined into
306   // the previously processed functions. Use external Visited set, which is
307   // also modified when we inline a function.
308   SmallPtrSet<CallGraphNode*,24> Visited;
309   while(!BFSQueue.empty()) {
310     CallGraphNode *N = BFSQueue.front();
311     BFSQueue.pop();
312 
313     // Skip the functions which have been processed already or previously
314     // inlined.
315     if (Visited.count(N))
316       continue;
317 
318     // Analyze the function.
319     SetOfDecls VisitedCallees;
320     Decl *D = N->getDecl();
321     assert(D);
322     HandleCode(D, ANALYSIS_PATH,
323                (Mgr->InliningMode == All ? 0 : &VisitedCallees));
324 
325     // Add the visited callees to the global visited set.
326     for (SetOfDecls::const_iterator I = VisitedCallees.begin(),
327                                     E = VisitedCallees.end(); I != E; ++I) {
328       CallGraphNode *VN = CG.getNode(*I);
329       if (VN)
330         Visited.insert(VN);
331     }
332     Visited.insert(N);
333 
334     // Push the children into the queue.
335     for (CallGraphNode::const_iterator CI = N->begin(),
336                                        CE = N->end(); CI != CE; ++CI) {
337       BFSQueue.push(*CI);
338     }
339   }
340 }
341 
342 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
343   // Don't run the actions if an error has occurred with parsing the file.
344   DiagnosticsEngine &Diags = PP.getDiagnostics();
345   if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
346     return;
347 
348   {
349     if (TUTotalTimer) TUTotalTimer->startTimer();
350 
351     // Introduce a scope to destroy BR before Mgr.
352     BugReporter BR(*Mgr);
353     TranslationUnitDecl *TU = C.getTranslationUnitDecl();
354     checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
355 
356     // Run the AST-only checks using the order in which functions are defined.
357     // If inlining is not turned on, use the simplest function order for path
358     // sensitive analyzes as well.
359     RecVisitorMode = (Mgr->shouldInlineCall() ? ANALYSIS_SYNTAX : ANALYSIS_ALL);
360     RecVisitorBR = &BR;
361     TraverseDecl(TU);
362 
363     if (Mgr->shouldInlineCall())
364       HandleDeclsGallGraph(TU);
365 
366     // After all decls handled, run checkers on the entire TranslationUnit.
367     checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
368 
369     RecVisitorBR = 0;
370   }
371 
372   // Explicitly destroy the PathDiagnosticConsumer.  This will flush its output.
373   // FIXME: This should be replaced with something that doesn't rely on
374   // side-effects in PathDiagnosticConsumer's destructor. This is required when
375   // used with option -disable-free.
376   Mgr.reset(NULL);
377 
378   if (TUTotalTimer) TUTotalTimer->stopTimer();
379 
380   // Count how many basic blocks we have not covered.
381   NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
382   if (NumBlocksInAnalyzedFunctions > 0)
383     PercentReachableBlocks =
384       (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
385         NumBlocksInAnalyzedFunctions;
386 
387 }
388 
389 static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) {
390   if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
391     WL.push_back(BD);
392 
393   for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
394        I!=E; ++I)
395     if (DeclContext *DC = dyn_cast<DeclContext>(*I))
396       FindBlocks(DC, WL);
397 }
398 
399 static std::string getFunctionName(const Decl *D) {
400   if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) {
401     return ID->getSelector().getAsString();
402   }
403   if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) {
404     IdentifierInfo *II = ND->getIdentifier();
405     if (II)
406       return II->getName();
407   }
408   return "";
409 }
410 
411 bool AnalysisConsumer::skipFunction(Decl *D) {
412   if (!Opts.AnalyzeSpecificFunction.empty() &&
413       getFunctionName(D) != Opts.AnalyzeSpecificFunction)
414     return true;
415 
416   // Don't run the actions on declarations in header files unless
417   // otherwise specified.
418   SourceManager &SM = Ctx->getSourceManager();
419   SourceLocation SL = SM.getExpansionLoc(D->getLocation());
420   if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL))
421     return true;
422 
423   return false;
424 }
425 
426 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
427                                   SetOfDecls *VisitedCallees) {
428   if (skipFunction(D))
429     return;
430 
431   DisplayFunction(D, Mode);
432 
433   // Clear the AnalysisManager of old AnalysisDeclContexts.
434   Mgr->ClearContexts();
435 
436   // Dispatch on the actions.
437   SmallVector<Decl*, 10> WL;
438   WL.push_back(D);
439 
440   if (D->hasBody() && Opts.AnalyzeNestedBlocks)
441     FindBlocks(cast<DeclContext>(D), WL);
442 
443   BugReporter BR(*Mgr);
444   for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
445        WI != WE; ++WI)
446     if ((*WI)->hasBody()) {
447       if (Mode != ANALYSIS_PATH)
448         checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
449       if (Mode != ANALYSIS_SYNTAX && checkerMgr->hasPathSensitiveCheckers()) {
450         RunPathSensitiveChecks(*WI, VisitedCallees);
451         NumFunctionsAnalyzed++;
452       }
453     }
454 }
455 
456 //===----------------------------------------------------------------------===//
457 // Path-sensitive checking.
458 //===----------------------------------------------------------------------===//
459 
460 void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled,
461                                         SetOfDecls *VisitedCallees) {
462   // Construct the analysis engine.  First check if the CFG is valid.
463   // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
464   if (!Mgr->getCFG(D))
465     return;
466 
467   ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries);
468 
469   // Set the graph auditor.
470   OwningPtr<ExplodedNode::Auditor> Auditor;
471   if (Mgr->shouldVisualizeUbigraph()) {
472     Auditor.reset(CreateUbiViz());
473     ExplodedNode::SetAuditor(Auditor.get());
474   }
475 
476   // Execute the worklist algorithm.
477   Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D, 0),
478                       Mgr->getMaxNodes());
479 
480   // Release the auditor (if any) so that it doesn't monitor the graph
481   // created BugReporter.
482   ExplodedNode::SetAuditor(0);
483 
484   // Visualize the exploded graph.
485   if (Mgr->shouldVisualizeGraphviz())
486     Eng.ViewGraph(Mgr->shouldTrimGraph());
487 
488   // Display warnings.
489   Eng.getBugReporter().FlushReports();
490 }
491 
492 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D, SetOfDecls *Visited) {
493 
494   switch (Mgr->getLangOpts().getGC()) {
495   case LangOptions::NonGC:
496     ActionExprEngine(D, false, Visited);
497     break;
498 
499   case LangOptions::GCOnly:
500     ActionExprEngine(D, true, Visited);
501     break;
502 
503   case LangOptions::HybridGC:
504     ActionExprEngine(D, false, Visited);
505     ActionExprEngine(D, true, Visited);
506     break;
507   }
508 }
509 
510 //===----------------------------------------------------------------------===//
511 // AnalysisConsumer creation.
512 //===----------------------------------------------------------------------===//
513 
514 ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
515                                           const std::string& outDir,
516                                           const AnalyzerOptions& opts,
517                                           ArrayRef<std::string> plugins) {
518   // Disable the effects of '-Werror' when using the AnalysisConsumer.
519   pp.getDiagnostics().setWarningsAsErrors(false);
520 
521   return new AnalysisConsumer(pp, outDir, opts, plugins);
522 }
523 
524 //===----------------------------------------------------------------------===//
525 // Ubigraph Visualization.  FIXME: Move to separate file.
526 //===----------------------------------------------------------------------===//
527 
528 namespace {
529 
530 class UbigraphViz : public ExplodedNode::Auditor {
531   OwningPtr<raw_ostream> Out;
532   llvm::sys::Path Dir, Filename;
533   unsigned Cntr;
534 
535   typedef llvm::DenseMap<void*,unsigned> VMap;
536   VMap M;
537 
538 public:
539   UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
540               llvm::sys::Path& filename);
541 
542   ~UbigraphViz();
543 
544   virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst);
545 };
546 
547 } // end anonymous namespace
548 
549 static ExplodedNode::Auditor* CreateUbiViz() {
550   std::string ErrMsg;
551 
552   llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
553   if (!ErrMsg.empty())
554     return 0;
555 
556   llvm::sys::Path Filename = Dir;
557   Filename.appendComponent("llvm_ubi");
558   Filename.makeUnique(true,&ErrMsg);
559 
560   if (!ErrMsg.empty())
561     return 0;
562 
563   llvm::errs() << "Writing '" << Filename.str() << "'.\n";
564 
565   OwningPtr<llvm::raw_fd_ostream> Stream;
566   Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
567 
568   if (!ErrMsg.empty())
569     return 0;
570 
571   return new UbigraphViz(Stream.take(), Dir, Filename);
572 }
573 
574 void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
575 
576   assert (Src != Dst && "Self-edges are not allowed.");
577 
578   // Lookup the Src.  If it is a new node, it's a root.
579   VMap::iterator SrcI= M.find(Src);
580   unsigned SrcID;
581 
582   if (SrcI == M.end()) {
583     M[Src] = SrcID = Cntr++;
584     *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
585   }
586   else
587     SrcID = SrcI->second;
588 
589   // Lookup the Dst.
590   VMap::iterator DstI= M.find(Dst);
591   unsigned DstID;
592 
593   if (DstI == M.end()) {
594     M[Dst] = DstID = Cntr++;
595     *Out << "('vertex', " << DstID << ")\n";
596   }
597   else {
598     // We have hit DstID before.  Change its style to reflect a cache hit.
599     DstID = DstI->second;
600     *Out << "('change_vertex_style', " << DstID << ", 1)\n";
601   }
602 
603   // Add the edge.
604   *Out << "('edge', " << SrcID << ", " << DstID
605        << ", ('arrow','true'), ('oriented', 'true'))\n";
606 }
607 
608 UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
609                          llvm::sys::Path& filename)
610   : Out(out), Dir(dir), Filename(filename), Cntr(0) {
611 
612   *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
613   *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
614           " ('size', '1.5'))\n";
615 }
616 
617 UbigraphViz::~UbigraphViz() {
618   Out.reset(0);
619   llvm::errs() << "Running 'ubiviz' program... ";
620   std::string ErrMsg;
621   llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
622   std::vector<const char*> args;
623   args.push_back(Ubiviz.c_str());
624   args.push_back(Filename.c_str());
625   args.push_back(0);
626 
627   if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
628     llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
629   }
630 
631   // Delete the directory.
632   Dir.eraseFromDisk(true);
633 }
634