<div dir="ltr"><br><div>Thanks again!  To answer your question, this code is intended for use both inside and outside of clang, as part of a long term project to deploy thread safety analysis to languages other than C++.  It can be used independently of clang with appropriate include magic, and I have test frameworks that test it as such; the std::ostream stuff is a relic of that.  I did not mean to submit the commented code.  :-)</div><div><br></div><div>  -DeLesley</div><div><br></div></div><div class="gmail_extra"><br><div class="gmail_quote">On Thu, Sep 11, 2014 at 1:03 PM, Justin Bogner <span dir="ltr"><<a href="mailto:mail@justinbogner.com" target="_blank">mail@justinbogner.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><span class="">DeLesley Hutchins <<a href="mailto:delesley@google.com">delesley@google.com</a>> writes:<br>
> Author: delesley<br>
> Date: Wed Sep 10 17:12:52 2014<br>
> New Revision: 217556<br>
><br>
> URL: <a href="http://llvm.org/viewvc/llvm-project?rev=217556&view=rev" target="_blank">http://llvm.org/viewvc/llvm-project?rev=217556&view=rev</a><br>
> Log:<br>
> Thread Safety Analysis: major update to thread safety TIL.<br>
<br>
</span>This was causing some bots to hang due to the implementation of<br>
operator<<(std::ostream&, StringRef) deciding to self recurse. I've<br>
attempted to fix that in r217621.<br>
<br>
I also noticed that you commented out a version of this same operator<<<br>
in ThreadSafetyTraverse.h that didn't have the recursion problem. Please<br>
don't commit commented out code - just remove it.<br>
<br>
Finally, is there a good reason this is using ostream rather than llvm's<br>
raw_ostream?<br>
<div><div class="h5"><br>
> Numerous changes, including:<br>
>   * Changed the way variables and instructions are handled in basic blocks to<br>
>     be more efficient.<br>
>   * Eliminated SExprRef.<br>
>   * Simplified futures.<br>
>   * Fixed documentation.<br>
>   * Compute dominator and post dominator trees.<br>
><br>
> Modified:<br>
>     cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyCommon.h<br>
>     cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyLogical.h<br>
>     cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyOps.def<br>
>     cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTIL.h<br>
>     cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h<br>
>     cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyUtil.h<br>
>     cfe/trunk/lib/Analysis/ThreadSafetyCommon.cpp<br>
>     cfe/trunk/lib/Analysis/ThreadSafetyTIL.cpp<br>
><br>
> Modified: cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyCommon.h<br>
> URL: <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyCommon.h?rev=217556&r1=217555&r2=217556&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyCommon.h?rev=217556&r1=217555&r2=217556&view=diff</a><br>
> ==============================================================================<br>
> --- cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyCommon.h (original)<br>
> +++ cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyCommon.h Wed Sep 10 17:12:52 2014<br>
> @@ -477,9 +477,9 @@ private:<br>
>                                             // Indexed by clang BlockID.<br>
><br>
>    LVarDefinitionMap CurrentLVarMap;<br>
> -  std::vector<til::Variable*> CurrentArguments;<br>
> -  std::vector<til::Variable*> CurrentInstructions;<br>
> -  std::vector<til::Variable*> IncompleteArgs;<br>
> +  std::vector<til::Phi*>   CurrentArguments;<br>
> +  std::vector<til::SExpr*> CurrentInstructions;<br>
> +  std::vector<til::Phi*>   IncompleteArgs;<br>
>    til::BasicBlock *CurrentBB;<br>
>    BlockInfo *CurrentBlockInfo;<br>
>  };<br>
><br>
> Modified: cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyLogical.h<br>
> URL: <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyLogical.h?rev=217556&r1=217555&r2=217556&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyLogical.h?rev=217556&r1=217555&r2=217556&view=diff</a><br>
> ==============================================================================<br>
> --- cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyLogical.h (original)<br>
> +++ cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyLogical.h Wed Sep 10 17:12:52 2014<br>
> @@ -41,13 +41,13 @@ private:<br>
>  };<br>
><br>
>  class Terminal : public LExpr {<br>
> -  til::SExprRef Expr;<br>
> +  til::SExpr *Expr;<br>
><br>
>  public:<br>
>    Terminal(til::SExpr *Expr) : LExpr(LExpr::Terminal), Expr(Expr) {}<br>
><br>
> -  const til::SExpr *expr() const { return Expr.get(); }<br>
> -  til::SExpr *expr() { return Expr.get(); }<br>
> +  const til::SExpr *expr() const { return Expr; }<br>
> +  til::SExpr *expr() { return Expr; }<br>
><br>
>    static bool classof(const LExpr *E) { return E->kind() == LExpr::Terminal; }<br>
>  };<br>
><br>
> Modified: cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyOps.def<br>
> URL: <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyOps.def?rev=217556&r1=217555&r2=217556&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyOps.def?rev=217556&r1=217555&r2=217556&view=diff</a><br>
> ==============================================================================<br>
> --- cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyOps.def (original)<br>
> +++ cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyOps.def Wed Sep 10 17:12:52 2014<br>
> @@ -44,8 +44,11 @@ TIL_OPCODE_DEF(Cast)<br>
>  TIL_OPCODE_DEF(SCFG)<br>
>  TIL_OPCODE_DEF(BasicBlock)<br>
>  TIL_OPCODE_DEF(Phi)<br>
> +<br>
> +// Terminator instructions<br>
>  TIL_OPCODE_DEF(Goto)<br>
>  TIL_OPCODE_DEF(Branch)<br>
> +TIL_OPCODE_DEF(Return)<br>
><br>
>  // pseudo-terms<br>
>  TIL_OPCODE_DEF(Identifier)<br>
><br>
> Modified: cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTIL.h<br>
> URL: <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTIL.h?rev=217556&r1=217555&r2=217556&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTIL.h?rev=217556&r1=217555&r2=217556&view=diff</a><br>
> ==============================================================================<br>
> --- cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTIL.h (original)<br>
> +++ cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTIL.h Wed Sep 10 17:12:52 2014<br>
> @@ -63,24 +63,27 @@ namespace threadSafety {<br>
>  namespace til {<br>
><br>
><br>
> +/// Enum for the different distinct classes of SExpr<br>
>  enum TIL_Opcode {<br>
>  #define TIL_OPCODE_DEF(X) COP_##X,<br>
>  #include "ThreadSafetyOps.def"<br>
>  #undef TIL_OPCODE_DEF<br>
>  };<br>
><br>
> +/// Opcode for unary arithmetic operations.<br>
>  enum TIL_UnaryOpcode : unsigned char {<br>
>    UOP_Minus,        //  -<br>
>    UOP_BitNot,       //  ~<br>
>    UOP_LogicNot      //  !<br>
>  };<br>
><br>
> +/// Opcode for binary arithmetic operations.<br>
>  enum TIL_BinaryOpcode : unsigned char {<br>
> +  BOP_Add,          //  +<br>
> +  BOP_Sub,          //  -<br>
>    BOP_Mul,          //  *<br>
>    BOP_Div,          //  /<br>
>    BOP_Rem,          //  %<br>
> -  BOP_Add,          //  +<br>
> -  BOP_Sub,          //  -<br>
>    BOP_Shl,          //  <<<br>
>    BOP_Shr,          //  >><br>
>    BOP_BitAnd,       //  &<br>
> @@ -90,10 +93,11 @@ enum TIL_BinaryOpcode : unsigned char {<br>
>    BOP_Neq,          //  !=<br>
>    BOP_Lt,           //  <<br>
>    BOP_Leq,          //  <=<br>
> -  BOP_LogicAnd,     //  &&<br>
> -  BOP_LogicOr       //  ||<br>
> +  BOP_LogicAnd,     //  &&  (no short-circuit)<br>
> +  BOP_LogicOr       //  ||  (no short-circuit)<br>
>  };<br>
><br>
> +/// Opcode for cast operations.<br>
>  enum TIL_CastOpcode : unsigned char {<br>
>    CAST_none = 0,<br>
>    CAST_extendNum,   // extend precision of numeric type<br>
> @@ -107,21 +111,24 @@ const TIL_Opcode       COP_Min  = COP_Fu<br>
>  const TIL_Opcode       COP_Max  = COP_Branch;<br>
>  const TIL_UnaryOpcode  UOP_Min  = UOP_Minus;<br>
>  const TIL_UnaryOpcode  UOP_Max  = UOP_LogicNot;<br>
> -const TIL_BinaryOpcode BOP_Min  = BOP_Mul;<br>
> +const TIL_BinaryOpcode BOP_Min  = BOP_Add;<br>
>  const TIL_BinaryOpcode BOP_Max  = BOP_LogicOr;<br>
>  const TIL_CastOpcode   CAST_Min = CAST_none;<br>
>  const TIL_CastOpcode   CAST_Max = CAST_toInt;<br>
><br>
> +/// Return the name of a unary opcode.<br>
>  StringRef getUnaryOpcodeString(TIL_UnaryOpcode Op);<br>
> +<br>
> +/// Return the name of a binary opcode.<br>
>  StringRef getBinaryOpcodeString(TIL_BinaryOpcode Op);<br>
><br>
><br>
> -// ValueTypes are data types that can actually be held in registers.<br>
> -// All variables and expressions must have a vBNF_Nonealue type.<br>
> -// Pointer types are further subdivided into the various heap-allocated<br>
> -// types, such as functions, records, etc.<br>
> -// Structured types that are passed by value (e.g. complex numbers)<br>
> -// require special handling; they use BT_ValueRef, and size ST_0.<br>
> +/// ValueTypes are data types that can actually be held in registers.<br>
> +/// All variables and expressions must have a value type.<br>
> +/// Pointer types are further subdivided into the various heap-allocated<br>
> +/// types, such as functions, records, etc.<br>
> +/// Structured types that are passed by value (e.g. complex numbers)<br>
> +/// require special handling; they use BT_ValueRef, and size ST_0.<br>
>  struct ValueType {<br>
>    enum BaseType : unsigned char {<br>
>      BT_Void = 0,<br>
> @@ -247,8 +254,10 @@ inline ValueType ValueType::getValueType<br>
>  }<br>
><br>
><br>
> +class BasicBlock;<br>
> +<br>
><br>
> -// Base class for AST nodes in the typed intermediate language.<br>
> +/// Base class for AST nodes in the typed intermediate language.<br>
>  class SExpr {<br>
>  public:<br>
>    TIL_Opcode opcode() const { return static_cast<TIL_Opcode>(Opcode); }<br>
> @@ -267,71 +276,47 @@ public:<br>
>    // template <class C> typename C::CType compare(CType* E, C& Cmp) {<br>
>    //   compare all subexpressions, following the comparator interface<br>
>    // }<br>
> -<br>
>    void *operator new(size_t S, MemRegionRef &R) {<br>
>      return ::operator new(S, R);<br>
>    }<br>
><br>
> -  // SExpr objects cannot be deleted.<br>
> +  /// SExpr objects cannot be deleted.<br>
>    // This declaration is public to workaround a gcc bug that breaks building<br>
>    // with REQUIRES_EH=1.<br>
>    void operator delete(void *) LLVM_DELETED_FUNCTION;<br>
><br>
> +  /// Returns the instruction ID for this expression.<br>
> +  /// All basic block instructions have a unique ID (i.e. virtual register).<br>
> +  unsigned id() const { return SExprID; }<br>
> +<br>
> +  /// Returns the block, if this is an instruction in a basic block,<br>
> +  /// otherwise returns null.<br>
> +  BasicBlock* block() const { return Block; }<br>
> +<br>
> +  /// Set the basic block and instruction ID for this expression.<br>
> +  void setID(BasicBlock *B, unsigned id) { Block = B; SExprID = id; }<br>
> +<br>
>  protected:<br>
> -  SExpr(TIL_Opcode Op) : Opcode(Op), Reserved(0), Flags(0) {}<br>
> -  SExpr(const SExpr &E) : Opcode(E.Opcode), Reserved(0), Flags(E.Flags) {}<br>
> +  SExpr(TIL_Opcode Op)<br>
> +    : Opcode(Op), Reserved(0), Flags(0), SExprID(0), Block(nullptr) {}<br>
> +  SExpr(const SExpr &E)<br>
> +    : Opcode(E.Opcode), Reserved(0), Flags(E.Flags), SExprID(0),<br>
> +      Block(nullptr) {}<br>
><br>
>    const unsigned char Opcode;<br>
>    unsigned char Reserved;<br>
>    unsigned short Flags;<br>
> +  unsigned SExprID;<br>
> +  BasicBlock* Block;<br>
><br>
>  private:<br>
>    SExpr() LLVM_DELETED_FUNCTION;<br>
><br>
> -  // SExpr objects must be created in an arena.<br>
> +  /// SExpr objects must be created in an arena.<br>
>    void *operator new(size_t) LLVM_DELETED_FUNCTION;<br>
>  };<br>
><br>
><br>
> -// Class for owning references to SExprs.<br>
> -// Includes attach/detach logic for counting variable references and lazy<br>
> -// rewriting strategies.<br>
> -class SExprRef {<br>
> -public:<br>
> -  SExprRef() : Ptr(nullptr) { }<br>
> -  SExprRef(std::nullptr_t P) : Ptr(nullptr) { }<br>
> -  SExprRef(SExprRef &&R) : Ptr(R.Ptr) { R.Ptr = nullptr; }<br>
> -<br>
> -  // Defined after Variable and Future, below.<br>
> -  inline SExprRef(SExpr *P);<br>
> -  inline ~SExprRef();<br>
> -<br>
> -  SExpr       *get()       { return Ptr; }<br>
> -  const SExpr *get() const { return Ptr; }<br>
> -<br>
> -  SExpr       *operator->()       { return get(); }<br>
> -  const SExpr *operator->() const { return get(); }<br>
> -<br>
> -  SExpr       &operator*()        { return *Ptr; }<br>
> -  const SExpr &operator*() const  { return *Ptr; }<br>
> -<br>
> -  bool operator==(const SExprRef &R) const { return Ptr == R.Ptr; }<br>
> -  bool operator!=(const SExprRef &R) const { return !operator==(R); }<br>
> -  bool operator==(const SExpr *P)    const { return Ptr == P; }<br>
> -  bool operator!=(const SExpr *P)    const { return !operator==(P); }<br>
> -  bool operator==(std::nullptr_t)    const { return Ptr == nullptr; }<br>
> -  bool operator!=(std::nullptr_t)    const { return Ptr != nullptr; }<br>
> -<br>
> -  inline void reset(SExpr *E);<br>
> -<br>
> -private:<br>
> -  inline void attach();<br>
> -  inline void detach();<br>
> -<br>
> -  SExpr *Ptr;<br>
> -};<br>
> -<br>
> -<br>
>  // Contains various helper functions for SExprs.<br>
>  namespace ThreadSafetyTIL {<br>
>    inline bool isTrivial(const SExpr *E) {<br>
> @@ -343,62 +328,64 @@ namespace ThreadSafetyTIL {<br>
>  // Nodes which declare variables<br>
>  class Function;<br>
>  class SFunction;<br>
> -class BasicBlock;<br>
>  class Let;<br>
><br>
><br>
> -// A named variable, e.g. "x".<br>
> -//<br>
> -// There are two distinct places in which a Variable can appear in the AST.<br>
> -// A variable declaration introduces a new variable, and can occur in 3 places:<br>
> -//   Let-expressions:           (Let (x = t) u)<br>
> -//   Functions:                 (Function (x : t) u)<br>
> -//   Self-applicable functions  (SFunction (x) t)<br>
> -//<br>
> -// If a variable occurs in any other location, it is a reference to an existing<br>
> -// variable declaration -- e.g. 'x' in (x * y + z). To save space, we don't<br>
> -// allocate a separate AST node for variable references; a reference is just a<br>
> -// pointer to the original declaration.<br>
> +/// A named variable, e.g. "x".<br>
> +///<br>
> +/// There are two distinct places in which a Variable can appear in the AST.<br>
> +/// A variable declaration introduces a new variable, and can occur in 3 places:<br>
> +///   Let-expressions:           (Let (x = t) u)<br>
> +///   Functions:                 (Function (x : t) u)<br>
> +///   Self-applicable functions  (SFunction (x) t)<br>
> +///<br>
> +/// If a variable occurs in any other location, it is a reference to an existing<br>
> +/// variable declaration -- e.g. 'x' in (x * y + z). To save space, we don't<br>
> +/// allocate a separate AST node for variable references; a reference is just a<br>
> +/// pointer to the original declaration.<br>
>  class Variable : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Variable; }<br>
><br>
> -  // Let-variable, function parameter, or self-variable<br>
>    enum VariableKind {<br>
> -    VK_Let,<br>
> -    VK_LetBB,<br>
> -    VK_Fun,<br>
> -    VK_SFun<br>
> +    VK_Let,  ///< Let-variable<br>
> +    VK_Fun,  ///< Function parameter<br>
> +    VK_SFun  ///< SFunction (self) parameter<br>
>    };<br>
><br>
> -  // These are defined after SExprRef contructor, below<br>
> -  inline Variable(SExpr *D, const clang::ValueDecl *Cvd = nullptr);<br>
> -  inline Variable(StringRef s, SExpr *D = nullptr);<br>
> -  inline Variable(const Variable &Vd, SExpr *D);<br>
> +  Variable(StringRef s, SExpr *D = nullptr)<br>
> +      : SExpr(COP_Variable), Name(s), Definition(D), Cvdecl(nullptr) {<br>
> +    Flags = VK_Let;<br>
> +  }<br>
> +  Variable(SExpr *D, const clang::ValueDecl *Cvd = nullptr)<br>
> +      : SExpr(COP_Variable), Name(Cvd ? Cvd->getName() : "_x"),<br>
> +        Definition(D), Cvdecl(Cvd) {<br>
> +    Flags = VK_Let;<br>
> +  }<br>
> +  Variable(const Variable &Vd, SExpr *D)  // rewrite constructor<br>
> +      : SExpr(Vd), Name(Vd.Name), Definition(D), Cvdecl(Vd.Cvdecl) {<br>
> +    Flags = Vd.kind();<br>
> +  }<br>
><br>
> +  /// Return the kind of variable (let, function param, or self)<br>
>    VariableKind kind() const { return static_cast<VariableKind>(Flags); }<br>
><br>
> +  /// Return the name of the variable, if any.<br>
>    StringRef name() const { return Name; }<br>
> +<br>
> +  /// Return the clang declaration for this variable, if any.<br>
>    const clang::ValueDecl *clangDecl() const { return Cvdecl; }<br>
><br>
> -  // Returns the definition (for let vars) or type (for parameter & self vars)<br>
> -  SExpr *definition() { return Definition.get(); }<br>
> -  const SExpr *definition() const { return Definition.get(); }<br>
> -<br>
> -  void attachVar() const { ++NumUses; }<br>
> -  void detachVar() const { assert(NumUses > 0); --NumUses; }<br>
> -<br>
> -  unsigned getID() const { return Id; }<br>
> -  unsigned getBlockID() const { return BlockID; }<br>
> -<br>
> -  void setName(StringRef S) { Name = S; }<br>
> -  void setID(unsigned Bid, unsigned I) {<br>
> -    BlockID = static_cast<unsigned short>(Bid);<br>
> -    Id = static_cast<unsigned short>(I);<br>
> -  }<br>
> -  void setClangDecl(const clang::ValueDecl *VD) { Cvdecl = VD; }<br>
> -  void setDefinition(SExpr *E);<br>
> +  /// Return the definition of the variable.<br>
> +  /// For let-vars, this is the setting expression.<br>
> +  /// For function and self parameters, it is the type of the variable.<br>
> +  SExpr *definition() { return Definition; }<br>
> +  const SExpr *definition() const { return Definition; }<br>
> +<br>
> +  void setName(StringRef S)    { Name = S;  }<br>
>    void setKind(VariableKind K) { Flags = K; }<br>
> +  void setDefinition(SExpr *E) { Definition = E; }<br>
> +  void setClangDecl(const clang::ValueDecl *VD) { Cvdecl = VD; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -418,17 +405,13 @@ private:<br>
>    friend class Let;<br>
><br>
>    StringRef Name;                  // The name of the variable.<br>
> -  SExprRef  Definition;            // The TIL type or definition<br>
> +  SExpr*    Definition;            // The TIL type or definition<br>
>    const clang::ValueDecl *Cvdecl;  // The clang declaration for this variable.<br>
> -<br>
> -  unsigned short BlockID;<br>
> -  unsigned short Id;<br>
> -  mutable unsigned NumUses;<br>
>  };<br>
><br>
><br>
> -// Placeholder for an expression that has not yet been created.<br>
> -// Used to implement lazy copy and rewriting strategies.<br>
> +/// Placeholder for an expression that has not yet been created.<br>
> +/// Used to implement lazy copy and rewriting strategies.<br>
>  class Future : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Future; }<br>
> @@ -439,22 +422,14 @@ public:<br>
>      FS_done<br>
>    };<br>
><br>
> -  Future() :<br>
> -    SExpr(COP_Future), Status(FS_pending), Result(nullptr), Location(nullptr)<br>
> -  {}<br>
> +  Future() : SExpr(COP_Future), Status(FS_pending), Result(nullptr) {}<br>
> +<br>
>  private:<br>
>    virtual ~Future() LLVM_DELETED_FUNCTION;<br>
> -public:<br>
> -<br>
> -  // Registers the location in the AST where this future is stored.<br>
> -  // Forcing the future will automatically update the AST.<br>
> -  static inline void registerLocation(SExprRef *Member) {<br>
> -    if (Future *F = dyn_cast_or_null<Future>(Member->get()))<br>
> -      F->Location = Member;<br>
> -  }<br>
><br>
> +public:<br>
>    // A lazy rewriting strategy should subclass Future and override this method.<br>
> -  virtual SExpr *create() { return nullptr; }<br>
> +  virtual SExpr *compute() { return nullptr; }<br>
><br>
>    // Return the result of this future if it exists, otherwise return null.<br>
>    SExpr *maybeGetResult() const {<br>
> @@ -465,8 +440,7 @@ public:<br>
>    SExpr *result() {<br>
>      switch (Status) {<br>
>      case FS_pending:<br>
> -      force();<br>
> -      return Result;<br>
> +      return force();<br>
>      case FS_evaluating:<br>
>        return nullptr; // infinite loop; illegal recursion.<br>
>      case FS_done:<br>
> @@ -488,81 +462,14 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  // Force the future.<br>
> -  inline void force();<br>
> +  SExpr* force();<br>
><br>
>    FutureStatus Status;<br>
>    SExpr *Result;<br>
> -  SExprRef *Location;<br>
>  };<br>
><br>
><br>
> -inline void SExprRef::attach() {<br>
> -  if (!Ptr)<br>
> -    return;<br>
> -<br>
> -  TIL_Opcode Op = Ptr->opcode();<br>
> -  if (Op == COP_Variable) {<br>
> -    cast<Variable>(Ptr)->attachVar();<br>
> -  } else if (Op == COP_Future) {<br>
> -    cast<Future>(Ptr)->registerLocation(this);<br>
> -  }<br>
> -}<br>
> -<br>
> -inline void SExprRef::detach() {<br>
> -  if (Ptr && Ptr->opcode() == COP_Variable) {<br>
> -    cast<Variable>(Ptr)->detachVar();<br>
> -  }<br>
> -}<br>
> -<br>
> -inline SExprRef::SExprRef(SExpr *P) : Ptr(P) {<br>
> -  attach();<br>
> -}<br>
> -<br>
> -inline SExprRef::~SExprRef() {<br>
> -  detach();<br>
> -}<br>
> -<br>
> -inline void SExprRef::reset(SExpr *P) {<br>
> -  detach();<br>
> -  Ptr = P;<br>
> -  attach();<br>
> -}<br>
> -<br>
> -<br>
> -inline Variable::Variable(StringRef s, SExpr *D)<br>
> -    : SExpr(COP_Variable), Name(s), Definition(D), Cvdecl(nullptr),<br>
> -      BlockID(0), Id(0), NumUses(0) {<br>
> -  Flags = VK_Let;<br>
> -}<br>
> -<br>
> -inline Variable::Variable(SExpr *D, const clang::ValueDecl *Cvd)<br>
> -    : SExpr(COP_Variable), Name(Cvd ? Cvd->getName() : "_x"),<br>
> -      Definition(D), Cvdecl(Cvd), BlockID(0), Id(0), NumUses(0) {<br>
> -  Flags = VK_Let;<br>
> -}<br>
> -<br>
> -inline Variable::Variable(const Variable &Vd, SExpr *D) // rewrite constructor<br>
> -    : SExpr(Vd), Name(Vd.Name), Definition(D), Cvdecl(Vd.Cvdecl),<br>
> -      BlockID(0), Id(0), NumUses(0) {<br>
> -  Flags = Vd.kind();<br>
> -}<br>
> -<br>
> -inline void Variable::setDefinition(SExpr *E) {<br>
> -  Definition.reset(E);<br>
> -}<br>
> -<br>
> -void Future::force() {<br>
> -  Status = FS_evaluating;<br>
> -  SExpr *R = create();<br>
> -  Result = R;<br>
> -  if (Location)<br>
> -    Location->reset(R);<br>
> -  Status = FS_done;<br>
> -}<br>
> -<br>
> -<br>
> -// Placeholder for C++ expressions that cannot be represented in the TIL.<br>
> +/// Placeholder for expressions that cannot be represented in the TIL.<br>
>  class Undefined : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Undefined; }<br>
> @@ -585,7 +492,7 @@ private:<br>
>  };<br>
><br>
><br>
> -// Placeholder for a wildcard that matches any other expression.<br>
> +/// Placeholder for a wildcard that matches any other expression.<br>
>  class Wildcard : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Wildcard; }<br>
> @@ -716,8 +623,8 @@ typename V::R_SExpr Literal::traverse(V<br>
>  }<br>
><br>
><br>
> -// Literal pointer to an object allocated in memory.<br>
> -// At compile time, pointer literals are represented by symbolic names.<br>
> +/// A Literal pointer to an object allocated in memory.<br>
> +/// At compile time, pointer literals are represented by symbolic names.<br>
>  class LiteralPtr : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_LiteralPtr; }<br>
> @@ -743,9 +650,9 @@ private:<br>
>  };<br>
><br>
><br>
> -// A function -- a.k.a. lambda abstraction.<br>
> -// Functions with multiple arguments are created by currying,<br>
> -// e.g. (function (x: Int) (function (y: Int) (add x y)))<br>
> +/// A function -- a.k.a. lambda abstraction.<br>
> +/// Functions with multiple arguments are created by currying,<br>
> +/// e.g. (Function (x: Int) (Function (y: Int) (Code { return x + y })))<br>
>  class Function : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Function; }<br>
> @@ -762,8 +669,8 @@ public:<br>
>    Variable *variableDecl()  { return VarDecl; }<br>
>    const Variable *variableDecl() const { return VarDecl; }<br>
><br>
> -  SExpr *body() { return Body.get(); }<br>
> -  const SExpr *body() const { return Body.get(); }<br>
> +  SExpr *body() { return Body; }<br>
> +  const SExpr *body() const { return Body; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -790,13 +697,13 @@ public:<br>
><br>
>  private:<br>
>    Variable *VarDecl;<br>
> -  SExprRef Body;<br>
> +  SExpr* Body;<br>
>  };<br>
><br>
><br>
> -// A self-applicable function.<br>
> -// A self-applicable function can be applied to itself.  It's useful for<br>
> -// implementing objects and late binding<br>
> +/// A self-applicable function.<br>
> +/// A self-applicable function can be applied to itself.  It's useful for<br>
> +/// implementing objects and late binding.<br>
>  class SFunction : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_SFunction; }<br>
> @@ -805,20 +712,20 @@ public:<br>
>        : SExpr(COP_SFunction), VarDecl(Vd), Body(B) {<br>
>      assert(Vd->Definition == nullptr);<br>
>      Vd->setKind(Variable::VK_SFun);<br>
> -    Vd->Definition.reset(this);<br>
> +    Vd->Definition = this;<br>
>    }<br>
>    SFunction(const SFunction &F, Variable *Vd, SExpr *B) // rewrite constructor<br>
>        : SExpr(F), VarDecl(Vd), Body(B) {<br>
>      assert(Vd->Definition == nullptr);<br>
>      Vd->setKind(Variable::VK_SFun);<br>
> -    Vd->Definition.reset(this);<br>
> +    Vd->Definition = this;<br>
>    }<br>
><br>
>    Variable *variableDecl() { return VarDecl; }<br>
>    const Variable *variableDecl() const { return VarDecl; }<br>
><br>
> -  SExpr *body() { return Body.get(); }<br>
> -  const SExpr *body() const { return Body.get(); }<br>
> +  SExpr *body() { return Body; }<br>
> +  const SExpr *body() const { return Body; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -842,11 +749,11 @@ public:<br>
><br>
>  private:<br>
>    Variable *VarDecl;<br>
> -  SExprRef Body;<br>
> +  SExpr* Body;<br>
>  };<br>
><br>
><br>
> -// A block of code -- e.g. the body of a function.<br>
> +/// A block of code -- e.g. the body of a function.<br>
>  class Code : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Code; }<br>
> @@ -855,11 +762,11 @@ public:<br>
>    Code(const Code &C, SExpr *T, SExpr *B) // rewrite constructor<br>
>        : SExpr(C), ReturnType(T), Body(B) {}<br>
><br>
> -  SExpr *returnType() { return ReturnType.get(); }<br>
> -  const SExpr *returnType() const { return ReturnType.get(); }<br>
> +  SExpr *returnType() { return ReturnType; }<br>
> +  const SExpr *returnType() const { return ReturnType; }<br>
><br>
> -  SExpr *body() { return Body.get(); }<br>
> -  const SExpr *body() const { return Body.get(); }<br>
> +  SExpr *body() { return Body; }<br>
> +  const SExpr *body() const { return Body; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -877,12 +784,12 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef ReturnType;<br>
> -  SExprRef Body;<br>
> +  SExpr* ReturnType;<br>
> +  SExpr* Body;<br>
>  };<br>
><br>
><br>
> -// A typed, writable location in memory<br>
> +/// A typed, writable location in memory<br>
>  class Field : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Field; }<br>
> @@ -891,11 +798,11 @@ public:<br>
>    Field(const Field &C, SExpr *R, SExpr *B) // rewrite constructor<br>
>        : SExpr(C), Range(R), Body(B) {}<br>
><br>
> -  SExpr *range() { return Range.get(); }<br>
> -  const SExpr *range() const { return Range.get(); }<br>
> +  SExpr *range() { return Range; }<br>
> +  const SExpr *range() const { return Range; }<br>
><br>
> -  SExpr *body() { return Body.get(); }<br>
> -  const SExpr *body() const { return Body.get(); }<br>
> +  SExpr *body() { return Body; }<br>
> +  const SExpr *body() const { return Body; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -913,12 +820,16 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Range;<br>
> -  SExprRef Body;<br>
> +  SExpr* Range;<br>
> +  SExpr* Body;<br>
>  };<br>
><br>
><br>
> -// Apply an argument to a function<br>
> +/// Apply an argument to a function.<br>
> +/// Note that this does not actually call the function.  Functions are curried,<br>
> +/// so this returns a closure in which the first parameter has been applied.<br>
> +/// Once all parameters have been applied, Call can be used to invoke the<br>
> +/// function.<br>
>  class Apply : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Apply; }<br>
> @@ -928,11 +839,11 @@ public:<br>
>        : SExpr(A), Fun(F), Arg(Ar)<br>
>    {}<br>
><br>
> -  SExpr *fun() { return Fun.get(); }<br>
> -  const SExpr *fun() const { return Fun.get(); }<br>
> +  SExpr *fun() { return Fun; }<br>
> +  const SExpr *fun() const { return Fun; }<br>
><br>
> -  SExpr *arg() { return Arg.get(); }<br>
> -  const SExpr *arg() const { return Arg.get(); }<br>
> +  SExpr *arg() { return Arg; }<br>
> +  const SExpr *arg() const { return Arg; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -950,12 +861,12 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Fun;<br>
> -  SExprRef Arg;<br>
> +  SExpr* Fun;<br>
> +  SExpr* Arg;<br>
>  };<br>
><br>
><br>
> -// Apply a self-argument to a self-applicable function<br>
> +/// Apply a self-argument to a self-applicable function.<br>
>  class SApply : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_SApply; }<br>
> @@ -964,18 +875,18 @@ public:<br>
>    SApply(SApply &A, SExpr *Sf, SExpr *Ar = nullptr) // rewrite constructor<br>
>        : SExpr(A), Sfun(Sf), Arg(Ar) {}<br>
><br>
> -  SExpr *sfun() { return Sfun.get(); }<br>
> -  const SExpr *sfun() const { return Sfun.get(); }<br>
> +  SExpr *sfun() { return Sfun; }<br>
> +  const SExpr *sfun() const { return Sfun; }<br>
><br>
> -  SExpr *arg() { return Arg.get() ? Arg.get() : Sfun.get(); }<br>
> -  const SExpr *arg() const { return Arg.get() ? Arg.get() : Sfun.get(); }<br>
> +  SExpr *arg() { return Arg ? Arg : Sfun; }<br>
> +  const SExpr *arg() const { return Arg ? Arg : Sfun; }<br>
><br>
>    bool isDelegation() const { return Arg != nullptr; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
>      auto Nf = Vs.traverse(Sfun, Vs.subExprCtx(Ctx));<br>
> -    typename V::R_SExpr Na = Arg.get() ? Vs.traverse(Arg, Vs.subExprCtx(Ctx))<br>
> +    typename V::R_SExpr Na = Arg ? Vs.traverse(Arg, Vs.subExprCtx(Ctx))<br>
>                                         : nullptr;<br>
>      return Vs.reduceSApply(*this, Nf, Na);<br>
>    }<br>
> @@ -989,12 +900,12 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Sfun;<br>
> -  SExprRef Arg;<br>
> +  SExpr* Sfun;<br>
> +  SExpr* Arg;<br>
>  };<br>
><br>
><br>
> -// Project a named slot from a C++ struct or class.<br>
> +/// Project a named slot from a C++ struct or class.<br>
>  class Project : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Project; }<br>
> @@ -1009,8 +920,8 @@ public:<br>
>        : SExpr(P), Rec(R), SlotName(P.SlotName), Cvdecl(P.Cvdecl)<br>
>    { }<br>
><br>
> -  SExpr *record() { return Rec.get(); }<br>
> -  const SExpr *record() const { return Rec.get(); }<br>
> +  SExpr *record() { return Rec; }<br>
> +  const SExpr *record() const { return Rec; }<br>
><br>
>    const clang::ValueDecl *clangDecl() const { return Cvdecl; }<br>
><br>
> @@ -1042,13 +953,13 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Rec;<br>
> +  SExpr* Rec;<br>
>    StringRef SlotName;<br>
>    const clang::ValueDecl *Cvdecl;<br>
>  };<br>
><br>
><br>
> -// Call a function (after all arguments have been applied).<br>
> +/// Call a function (after all arguments have been applied).<br>
>  class Call : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Call; }<br>
> @@ -1057,8 +968,8 @@ public:<br>
>        : SExpr(COP_Call), Target(T), Cexpr(Ce) {}<br>
>    Call(const Call &C, SExpr *T) : SExpr(C), Target(T), Cexpr(C.Cexpr) {}<br>
><br>
> -  SExpr *target() { return Target.get(); }<br>
> -  const SExpr *target() const { return Target.get(); }<br>
> +  SExpr *target() { return Target; }<br>
> +  const SExpr *target() const { return Target; }<br>
><br>
>    const clang::CallExpr *clangCallExpr() const { return Cexpr; }<br>
><br>
> @@ -1074,12 +985,12 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Target;<br>
> +  SExpr* Target;<br>
>    const clang::CallExpr *Cexpr;<br>
>  };<br>
><br>
><br>
> -// Allocate memory for a new value on the heap or stack.<br>
> +/// Allocate memory for a new value on the heap or stack.<br>
>  class Alloc : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Call; }<br>
> @@ -1094,8 +1005,8 @@ public:<br>
><br>
>    AllocKind kind() const { return static_cast<AllocKind>(Flags); }<br>
><br>
> -  SExpr *dataType() { return Dtype.get(); }<br>
> -  const SExpr *dataType() const { return Dtype.get(); }<br>
> +  SExpr *dataType() { return Dtype; }<br>
> +  const SExpr *dataType() const { return Dtype; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -1112,11 +1023,11 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Dtype;<br>
> +  SExpr* Dtype;<br>
>  };<br>
><br>
><br>
> -// Load a value from memory.<br>
> +/// Load a value from memory.<br>
>  class Load : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Load; }<br>
> @@ -1124,8 +1035,8 @@ public:<br>
>    Load(SExpr *P) : SExpr(COP_Load), Ptr(P) {}<br>
>    Load(const Load &L, SExpr *P) : SExpr(L), Ptr(P) {}<br>
><br>
> -  SExpr *pointer() { return Ptr.get(); }<br>
> -  const SExpr *pointer() const { return Ptr.get(); }<br>
> +  SExpr *pointer() { return Ptr; }<br>
> +  const SExpr *pointer() const { return Ptr; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -1139,12 +1050,12 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Ptr;<br>
> +  SExpr* Ptr;<br>
>  };<br>
><br>
><br>
> -// Store a value to memory.<br>
> -// Source is a pointer, destination is the value to store.<br>
> +/// Store a value to memory.<br>
> +/// The destination is a pointer to a field, the source is the value to store.<br>
>  class Store : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Store; }<br>
> @@ -1152,11 +1063,11 @@ public:<br>
>    Store(SExpr *P, SExpr *V) : SExpr(COP_Store), Dest(P), Source(V) {}<br>
>    Store(const Store &S, SExpr *P, SExpr *V) : SExpr(S), Dest(P), Source(V) {}<br>
><br>
> -  SExpr *destination() { return Dest.get(); }  // Address to store to<br>
> -  const SExpr *destination() const { return Dest.get(); }<br>
> +  SExpr *destination() { return Dest; }  // Address to store to<br>
> +  const SExpr *destination() const { return Dest; }<br>
><br>
> -  SExpr *source() { return Source.get(); }     // Value to store<br>
> -  const SExpr *source() const { return Source.get(); }<br>
> +  SExpr *source() { return Source; }     // Value to store<br>
> +  const SExpr *source() const { return Source; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -1174,13 +1085,13 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Dest;<br>
> -  SExprRef Source;<br>
> +  SExpr* Dest;<br>
> +  SExpr* Source;<br>
>  };<br>
><br>
><br>
> -// If p is a reference to an array, then first(p) is a reference to the first<br>
> -// element.  The usual array notation p[i]  becomes first(p + i).<br>
> +/// If p is a reference to an array, then p[i] is a reference to the i'th<br>
> +/// element of the array.<br>
>  class ArrayIndex : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_ArrayIndex; }<br>
> @@ -1189,11 +1100,11 @@ public:<br>
>    ArrayIndex(const ArrayIndex &E, SExpr *A, SExpr *N)<br>
>      : SExpr(E), Array(A), Index(N) {}<br>
><br>
> -  SExpr *array() { return Array.get(); }<br>
> -  const SExpr *array() const { return Array.get(); }<br>
> +  SExpr *array() { return Array; }<br>
> +  const SExpr *array() const { return Array; }<br>
><br>
> -  SExpr *index() { return Index.get(); }<br>
> -  const SExpr *index() const { return Index.get(); }<br>
> +  SExpr *index() { return Index; }<br>
> +  const SExpr *index() const { return Index; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -1211,14 +1122,14 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Array;<br>
> -  SExprRef Index;<br>
> +  SExpr* Array;<br>
> +  SExpr* Index;<br>
>  };<br>
><br>
><br>
> -// Pointer arithmetic, restricted to arrays only.<br>
> -// If p is a reference to an array, then p + n, where n is an integer, is<br>
> -// a reference to a subarray.<br>
> +/// Pointer arithmetic, restricted to arrays only.<br>
> +/// If p is a reference to an array, then p + n, where n is an integer, is<br>
> +/// a reference to a subarray.<br>
>  class ArrayAdd : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_ArrayAdd; }<br>
> @@ -1227,11 +1138,11 @@ public:<br>
>    ArrayAdd(const ArrayAdd &E, SExpr *A, SExpr *N)<br>
>      : SExpr(E), Array(A), Index(N) {}<br>
><br>
> -  SExpr *array() { return Array.get(); }<br>
> -  const SExpr *array() const { return Array.get(); }<br>
> +  SExpr *array() { return Array; }<br>
> +  const SExpr *array() const { return Array; }<br>
><br>
> -  SExpr *index() { return Index.get(); }<br>
> -  const SExpr *index() const { return Index.get(); }<br>
> +  SExpr *index() { return Index; }<br>
> +  const SExpr *index() const { return Index; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -1249,12 +1160,13 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Array;<br>
> -  SExprRef Index;<br>
> +  SExpr* Array;<br>
> +  SExpr* Index;<br>
>  };<br>
><br>
><br>
> -// Simple unary operation -- e.g. !, ~, etc.<br>
> +/// Simple arithmetic unary operations, e.g. negate and not.<br>
> +/// These operations have no side-effects.<br>
>  class UnaryOp : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_UnaryOp; }<br>
> @@ -1268,8 +1180,8 @@ public:<br>
>      return static_cast<TIL_UnaryOpcode>(Flags);<br>
>    }<br>
><br>
> -  SExpr *expr() { return Expr0.get(); }<br>
> -  const SExpr *expr() const { return Expr0.get(); }<br>
> +  SExpr *expr() { return Expr0; }<br>
> +  const SExpr *expr() const { return Expr0; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -1287,11 +1199,12 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Expr0;<br>
> +  SExpr* Expr0;<br>
>  };<br>
><br>
><br>
> -// Simple binary operation -- e.g. +, -, etc.<br>
> +/// Simple arithmetic binary operations, e.g. +, -, etc.<br>
> +/// These operations have no side effects.<br>
>  class BinaryOp : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_BinaryOp; }<br>
> @@ -1309,11 +1222,11 @@ public:<br>
>      return static_cast<TIL_BinaryOpcode>(Flags);<br>
>    }<br>
><br>
> -  SExpr *expr0() { return Expr0.get(); }<br>
> -  const SExpr *expr0() const { return Expr0.get(); }<br>
> +  SExpr *expr0() { return Expr0; }<br>
> +  const SExpr *expr0() const { return Expr0; }<br>
><br>
> -  SExpr *expr1() { return Expr1.get(); }<br>
> -  const SExpr *expr1() const { return Expr1.get(); }<br>
> +  SExpr *expr1() { return Expr1; }<br>
> +  const SExpr *expr1() const { return Expr1; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -1335,12 +1248,14 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Expr0;<br>
> -  SExprRef Expr1;<br>
> +  SExpr* Expr0;<br>
> +  SExpr* Expr1;<br>
>  };<br>
><br>
><br>
> -// Cast expression<br>
> +/// Cast expressions.<br>
> +/// Cast expressions are essentially unary operations, but we treat them<br>
> +/// as a distinct AST node because they only change the type of the result.<br>
>  class Cast : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Cast; }<br>
> @@ -1352,8 +1267,8 @@ public:<br>
>      return static_cast<TIL_CastOpcode>(Flags);<br>
>    }<br>
><br>
> -  SExpr *expr() { return Expr0.get(); }<br>
> -  const SExpr *expr() const { return Expr0.get(); }<br>
> +  SExpr *expr() { return Expr0; }<br>
> +  const SExpr *expr() const { return Expr0; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -1371,16 +1286,18 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Expr0;<br>
> +  SExpr* Expr0;<br>
>  };<br>
><br>
><br>
>  class SCFG;<br>
><br>
><br>
> +/// Phi Node, for code in SSA form.<br>
> +/// Each Phi node has an array of possible values that it can take,<br>
> +/// depending on where control flow comes from.<br>
>  class Phi : public SExpr {<br>
>  public:<br>
> -  // TODO: change to SExprRef<br>
>    typedef SimpleArray<SExpr *> ValArray;<br>
><br>
>    // In minimal SSA form, all Phi nodes are MultiVal.<br>
> @@ -1394,9 +1311,12 @@ public:<br>
><br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Phi; }<br>
><br>
> -  Phi() : SExpr(COP_Phi) {}<br>
> -  Phi(MemRegionRef A, unsigned Nvals) : SExpr(COP_Phi), Values(A, Nvals) {}<br>
> -  Phi(const Phi &P, ValArray &&Vs)    : SExpr(P), Values(std::move(Vs)) {}<br>
> +  Phi()<br>
> +    : SExpr(COP_Phi), Cvdecl(nullptr) {}<br>
> +  Phi(MemRegionRef A, unsigned Nvals)<br>
> +    : SExpr(COP_Phi), Values(A, Nvals), Cvdecl(nullptr)  {}<br>
> +  Phi(const Phi &P, ValArray &&Vs)<br>
> +    : SExpr(P), Values(std::move(Vs)), Cvdecl(nullptr) {}<br>
><br>
>    const ValArray &values() const { return Values; }<br>
>    ValArray &values() { return Values; }<br>
> @@ -1404,6 +1324,12 @@ public:<br>
>    Status status() const { return static_cast<Status>(Flags); }<br>
>    void setStatus(Status s) { Flags = s; }<br>
><br>
> +  /// Return the clang declaration of the variable for this Phi node, if any.<br>
> +  const clang::ValueDecl *clangDecl() const { return Cvdecl; }<br>
> +<br>
> +  /// Set the clang variable associated with this Phi node.<br>
> +  void setClangDecl(const clang::ValueDecl *Cvd) { Cvdecl = Cvd; }<br>
> +<br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
>      typename V::template Container<typename V::R_SExpr><br>
> @@ -1423,65 +1349,260 @@ public:<br>
><br>
>  private:<br>
>    ValArray Values;<br>
> +  const clang::ValueDecl* Cvdecl;<br>
> +};<br>
> +<br>
> +<br>
> +/// Base class for basic block terminators:  Branch, Goto, and Return.<br>
> +class Terminator : public SExpr {<br>
> +public:<br>
> +  static bool classof(const SExpr *E) {<br>
> +    return E->opcode() >= COP_Goto && E->opcode() <= COP_Return;<br>
> +  }<br>
> +<br>
> +protected:<br>
> +  Terminator(TIL_Opcode Op)  : SExpr(Op) {}<br>
> +  Terminator(const SExpr &E) : SExpr(E)  {}<br>
> +<br>
> +public:<br>
> +  /// Return the list of basic blocks that this terminator can branch to.<br>
> +  ArrayRef<BasicBlock*> successors();<br>
> +<br>
> +  ArrayRef<BasicBlock*> successors() const {<br>
> +    return const_cast<const Terminator*>(this)->successors();<br>
> +  }<br>
> +};<br>
> +<br>
> +<br>
> +/// Jump to another basic block.<br>
> +/// A goto instruction is essentially a tail-recursive call into another<br>
> +/// block.  In addition to the block pointer, it specifies an index into the<br>
> +/// phi nodes of that block.  The index can be used to retrieve the "arguments"<br>
> +/// of the call.<br>
> +class Goto : public Terminator {<br>
> +public:<br>
> +  static bool classof(const SExpr *E) { return E->opcode() == COP_Goto; }<br>
> +<br>
> +  Goto(BasicBlock *B, unsigned I)<br>
> +      : Terminator(COP_Goto), TargetBlock(B), Index(I) {}<br>
> +  Goto(const Goto &G, BasicBlock *B, unsigned I)<br>
> +      : Terminator(COP_Goto), TargetBlock(B), Index(I) {}<br>
> +<br>
> +  const BasicBlock *targetBlock() const { return TargetBlock; }<br>
> +  BasicBlock *targetBlock() { return TargetBlock; }<br>
> +<br>
> +  /// Returns the index into the<br>
> +  unsigned index() const { return Index; }<br>
> +<br>
> +  /// Return the list of basic blocks that this terminator can branch to.<br>
> +  ArrayRef<BasicBlock*> successors() {<br>
> +    return ArrayRef<BasicBlock*>(&TargetBlock, 1);<br>
> +  }<br>
> +<br>
> +  template <class V><br>
> +  typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> +    BasicBlock *Ntb = Vs.reduceBasicBlockRef(TargetBlock);<br>
> +    return Vs.reduceGoto(*this, Ntb);<br>
> +  }<br>
> +<br>
> +  template <class C><br>
> +  typename C::CType compare(const Goto *E, C &Cmp) const {<br>
> +    // TODO: implement CFG comparisons<br>
> +    return Cmp.comparePointers(this, E);<br>
> +  }<br>
> +<br>
> +private:<br>
> +  BasicBlock *TargetBlock;<br>
> +  unsigned Index;<br>
> +};<br>
> +<br>
> +<br>
> +/// A conditional branch to two other blocks.<br>
> +/// Note that unlike Goto, Branch does not have an index.  The target blocks<br>
> +/// must be child-blocks, and cannot have Phi nodes.<br>
> +class Branch : public Terminator {<br>
> +public:<br>
> +  static bool classof(const SExpr *E) { return E->opcode() == COP_Branch; }<br>
> +<br>
> +  Branch(SExpr *C, BasicBlock *T, BasicBlock *E)<br>
> +      : Terminator(COP_Branch), Condition(C) {<br>
> +    Branches[0] = T;<br>
> +    Branches[1] = E;<br>
> +  }<br>
> +  Branch(const Branch &Br, SExpr *C, BasicBlock *T, BasicBlock *E)<br>
> +      : Terminator(Br), Condition(C) {<br>
> +    Branches[0] = T;<br>
> +    Branches[1] = E;<br>
> +  }<br>
> +<br>
> +  const SExpr *condition() const { return Condition; }<br>
> +  SExpr *condition() { return Condition; }<br>
> +<br>
> +  const BasicBlock *thenBlock() const { return Branches[0]; }<br>
> +  BasicBlock *thenBlock() { return Branches[0]; }<br>
> +<br>
> +  const BasicBlock *elseBlock() const { return Branches[1]; }<br>
> +  BasicBlock *elseBlock() { return Branches[1]; }<br>
> +<br>
> +  /// Return the list of basic blocks that this terminator can branch to.<br>
> +  ArrayRef<BasicBlock*> successors() {<br>
> +    return ArrayRef<BasicBlock*>(Branches, 2);<br>
> +  }<br>
> +<br>
> +  template <class V><br>
> +  typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> +    auto Nc = Vs.traverse(Condition, Vs.subExprCtx(Ctx));<br>
> +    BasicBlock *Ntb = Vs.reduceBasicBlockRef(Branches[0]);<br>
> +    BasicBlock *Nte = Vs.reduceBasicBlockRef(Branches[1]);<br>
> +    return Vs.reduceBranch(*this, Nc, Ntb, Nte);<br>
> +  }<br>
> +<br>
> +  template <class C><br>
> +  typename C::CType compare(const Branch *E, C &Cmp) const {<br>
> +    // TODO: implement CFG comparisons<br>
> +    return Cmp.comparePointers(this, E);<br>
> +  }<br>
> +<br>
> +private:<br>
> +  SExpr*     Condition;<br>
> +  BasicBlock *Branches[2];<br>
> +};<br>
> +<br>
> +<br>
> +/// Return from the enclosing function, passing the return value to the caller.<br>
> +/// Only the exit block should end with a return statement.<br>
> +class Return : public Terminator {<br>
> +public:<br>
> +  static bool classof(const SExpr *E) { return E->opcode() == COP_Return; }<br>
> +<br>
> +  Return(SExpr* Rval) : Terminator(COP_Return), Retval(Rval) {}<br>
> +  Return(const Return &R, SExpr* Rval) : Terminator(R), Retval(Rval) {}<br>
> +<br>
> +  /// Return an empty list.<br>
> +  ArrayRef<BasicBlock*> successors() {<br>
> +    return ArrayRef<BasicBlock*>();<br>
> +  }<br>
> +<br>
> +  SExpr *returnValue() { return Retval; }<br>
> +  const SExpr *returnValue() const { return Retval; }<br>
> +<br>
> +  template <class V><br>
> +  typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> +    auto Ne = Vs.traverse(Retval, Vs.subExprCtx(Ctx));<br>
> +    return Vs.reduceReturn(*this, Ne);<br>
> +  }<br>
> +<br>
> +  template <class C><br>
> +  typename C::CType compare(const Return *E, C &Cmp) const {<br>
> +    return Cmp.compare(Retval, E->Retval);<br>
> +  }<br>
> +<br>
> +private:<br>
> +  SExpr* Retval;<br>
>  };<br>
><br>
><br>
> -// A basic block is part of an SCFG, and can be treated as a function in<br>
> -// continuation passing style.  It consists of a sequence of phi nodes, which<br>
> -// are "arguments" to the function, followed by a sequence of instructions.<br>
> -// Both arguments and instructions define new variables.  It ends with a<br>
> -// branch or goto to another basic block in the same SCFG.<br>
> +inline ArrayRef<BasicBlock*> Terminator::successors() {<br>
> +  switch (opcode()) {<br>
> +    case COP_Goto:   return cast<Goto>(this)->successors();<br>
> +    case COP_Branch: return cast<Branch>(this)->successors();<br>
> +    case COP_Return: return cast<Return>(this)->successors();<br>
> +    default:<br>
> +      return ArrayRef<BasicBlock*>();<br>
> +  }<br>
> +}<br>
> +<br>
> +<br>
> +/// A basic block is part of an SCFG.  It can be treated as a function in<br>
> +/// continuation passing style.  A block consists of a sequence of phi nodes,<br>
> +/// which are "arguments" to the function, followed by a sequence of<br>
> +/// instructions.  It ends with a Terminator, which is a Branch or Goto to<br>
> +/// another basic block in the same SCFG.<br>
>  class BasicBlock : public SExpr {<br>
>  public:<br>
> -  typedef SimpleArray<Variable*>   VarArray;<br>
> +  typedef SimpleArray<SExpr*>      InstrArray;<br>
>    typedef SimpleArray<BasicBlock*> BlockArray;<br>
><br>
> +  // TopologyNodes are used to overlay tree structures on top of the CFG,<br>
> +  // such as dominator and postdominator trees.  Each block is assigned an<br>
> +  // ID in the tree according to a depth-first search.  Tree traversals are<br>
> +  // always up, towards the parents.<br>
> +  struct TopologyNode {<br>
> +    TopologyNode() : NodeID(0), SizeOfSubTree(0), Parent(nullptr) {}<br>
> +<br>
> +    bool isParentOf(const TopologyNode& OtherNode) {<br>
> +      return OtherNode.NodeID > NodeID &&<br>
> +             OtherNode.NodeID < NodeID + SizeOfSubTree;<br>
> +    }<br>
> +<br>
> +    bool isParentOfOrEqual(const TopologyNode& OtherNode) {<br>
> +      return OtherNode.NodeID >= NodeID &&<br>
> +             OtherNode.NodeID < NodeID + SizeOfSubTree;<br>
> +    }<br>
> +<br>
> +    int NodeID;<br>
> +    int SizeOfSubTree;    // Includes this node, so must be > 1.<br>
> +    BasicBlock *Parent;   // Pointer to parent.<br>
> +  };<br>
> +<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_BasicBlock; }<br>
><br>
> -  explicit BasicBlock(MemRegionRef A, BasicBlock* P = nullptr)<br>
> +  explicit BasicBlock(MemRegionRef A)<br>
>        : SExpr(COP_BasicBlock), Arena(A), CFGPtr(nullptr), BlockID(0),<br>
> -        Parent(P), Terminator(nullptr)<br>
> -  { }<br>
> -  BasicBlock(BasicBlock &B, VarArray &&As, VarArray &&Is, SExpr *T)<br>
> -      : SExpr(COP_BasicBlock), Arena(B.Arena), CFGPtr(nullptr), BlockID(0),<br>
> -        Parent(nullptr), Args(std::move(As)), Instrs(std::move(Is)),<br>
> -        Terminator(T)<br>
> -  { }<br>
> -<br>
> -  unsigned blockID() const { return BlockID; }<br>
> -  unsigned numPredecessors() const { return Predecessors.size(); }<br>
> +        Visited(0), TermInstr(nullptr) {}<br>
> +  BasicBlock(BasicBlock &B, MemRegionRef A, InstrArray &&As, InstrArray &&Is,<br>
> +             Terminator *T)<br>
> +      : SExpr(COP_BasicBlock), Arena(A), CFGPtr(nullptr), BlockID(0),Visited(0),<br>
> +        Args(std::move(As)), Instrs(std::move(Is)), TermInstr(T) {}<br>
> +<br>
> +  /// Returns the block ID.  Every block has a unique ID in the CFG.<br>
> +  int blockID() const { return BlockID; }<br>
> +<br>
> +  /// Returns the number of predecessors.<br>
> +  size_t numPredecessors() const { return Predecessors.size(); }<br>
> +  size_t numSuccessors() const { return successors().size(); }<br>
><br>
>    const SCFG* cfg() const { return CFGPtr; }<br>
>    SCFG* cfg() { return CFGPtr; }<br>
><br>
> -  const BasicBlock *parent() const { return Parent; }<br>
> -  BasicBlock *parent() { return Parent; }<br>
> +  const BasicBlock *parent() const { return DominatorNode.Parent; }<br>
> +  BasicBlock *parent() { return DominatorNode.Parent; }<br>
><br>
> -  const VarArray &arguments() const { return Args; }<br>
> -  VarArray &arguments() { return Args; }<br>
> +  const InstrArray &arguments() const { return Args; }<br>
> +  InstrArray &arguments() { return Args; }<br>
><br>
> -  const VarArray &instructions() const { return Instrs; }<br>
> -  VarArray &instructions() { return Instrs; }<br>
> +  InstrArray &instructions() { return Instrs; }<br>
> +  const InstrArray &instructions() const { return Instrs; }<br>
><br>
> -  const BlockArray &predecessors() const { return Predecessors; }<br>
> +  /// Returns a list of predecessors.<br>
> +  /// The order of predecessors in the list is important; each phi node has<br>
> +  /// exactly one argument for each precessor, in the same order.<br>
>    BlockArray &predecessors() { return Predecessors; }<br>
> +  const BlockArray &predecessors() const { return Predecessors; }<br>
> +<br>
> +  ArrayRef<BasicBlock*> successors() { return TermInstr->successors(); }<br>
> +  ArrayRef<BasicBlock*> successors() const { return TermInstr->successors(); }<br>
><br>
> -  const SExpr *terminator() const { return Terminator.get(); }<br>
> -  SExpr *terminator() { return Terminator.get(); }<br>
> +  const Terminator *terminator() const { return TermInstr; }<br>
> +  Terminator *terminator() { return TermInstr; }<br>
><br>
> -  void setBlockID(unsigned i)   { BlockID = i; }<br>
> -  void setParent(BasicBlock *P) { Parent = P;  }<br>
> -  void setTerminator(SExpr *E)  { Terminator.reset(E); }<br>
> -<br>
> -  // Add a new argument.  V must define a phi-node.<br>
> -  void addArgument(Variable *V) {<br>
> -    V->setKind(Variable::VK_LetBB);<br>
> +  void setTerminator(Terminator *E) { TermInstr = E; }<br>
> +<br>
> +  bool Dominates(const BasicBlock &Other) {<br>
> +    return DominatorNode.isParentOfOrEqual(Other.DominatorNode);<br>
> +  }<br>
> +<br>
> +  bool PostDominates(const BasicBlock &Other) {<br>
> +    return PostDominatorNode.isParentOfOrEqual(Other.PostDominatorNode);<br>
> +  }<br>
> +<br>
> +  /// Add a new argument.<br>
> +  void addArgument(Phi *V) {<br>
>      Args.reserveCheck(1, Arena);<br>
>      Args.push_back(V);<br>
>    }<br>
> -  // Add a new instruction.<br>
> -  void addInstruction(Variable *V) {<br>
> -    V->setKind(Variable::VK_LetBB);<br>
> +  /// Add a new instruction.<br>
> +  void addInstruction(SExpr *V) {<br>
>      Instrs.reserveCheck(1, Arena);<br>
>      Instrs.push_back(V);<br>
>    }<br>
> @@ -1498,34 +1619,29 @@ public:<br>
>    // Reserve space for NumPreds predecessors, including space in phi nodes.<br>
>    void reservePredecessors(unsigned NumPreds);<br>
><br>
> -  // Return the index of BB, or Predecessors.size if BB is not a predecessor.<br>
> +  /// Return the index of BB, or Predecessors.size if BB is not a predecessor.<br>
>    unsigned findPredecessorIndex(const BasicBlock *BB) const {<br>
>      auto I = std::find(Predecessors.cbegin(), Predecessors.cend(), BB);<br>
>      return std::distance(Predecessors.cbegin(), I);<br>
>    }<br>
><br>
> -  // Set id numbers for variables.<br>
> -  void renumberVars();<br>
> -<br>
>    template <class V><br>
>    typename V::R_BasicBlock traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> -    typename V::template Container<Variable*> Nas(Vs, Args.size());<br>
> -    typename V::template Container<Variable*> Nis(Vs, Instrs.size());<br>
> +    typename V::template Container<SExpr*> Nas(Vs, Args.size());<br>
> +    typename V::template Container<SExpr*> Nis(Vs, Instrs.size());<br>
><br>
>      // Entering the basic block should do any scope initialization.<br>
>      Vs.enterBasicBlock(*this);<br>
><br>
> -    for (auto *A : Args) {<br>
> -      auto Ne = Vs.traverse(A->Definition, Vs.subExprCtx(Ctx));<br>
> -      Variable *Nvd = Vs.enterScope(*A, Ne);<br>
> -      Nas.push_back(Nvd);<br>
> +    for (auto *E : Args) {<br>
> +      auto Ne = Vs.traverse(E, Vs.subExprCtx(Ctx));<br>
> +      Nas.push_back(Ne);<br>
>      }<br>
> -    for (auto *I : Instrs) {<br>
> -      auto Ne = Vs.traverse(I->Definition, Vs.subExprCtx(Ctx));<br>
> -      Variable *Nvd = Vs.enterScope(*I, Ne);<br>
> -      Nis.push_back(Nvd);<br>
> +    for (auto *E : Instrs) {<br>
> +      auto Ne = Vs.traverse(E, Vs.subExprCtx(Ctx));<br>
> +      Nis.push_back(Ne);<br>
>      }<br>
> -    auto Nt = Vs.traverse(Terminator, Ctx);<br>
> +    auto Nt = Vs.traverse(TermInstr, Ctx);<br>
><br>
>      // Exiting the basic block should handle any scope cleanup.<br>
>      Vs.exitBasicBlock(*this);<br>
> @@ -1542,22 +1658,32 @@ public:<br>
>  private:<br>
>    friend class SCFG;<br>
><br>
> -  MemRegionRef Arena;<br>
> -<br>
> -  SCFG       *CFGPtr;       // The CFG that contains this block.<br>
> -  unsigned   BlockID;       // unique id for this BB in the containing CFG<br>
> -  BasicBlock *Parent;       // The parent block is the enclosing lexical scope.<br>
> -                            // The parent dominates this block.<br>
> -  BlockArray Predecessors;  // Predecessor blocks in the CFG.<br>
> -  VarArray   Args;          // Phi nodes.  One argument per predecessor.<br>
> -  VarArray   Instrs;        // Instructions.<br>
> -  SExprRef   Terminator;    // Branch or Goto<br>
> +  int  renumberInstrs(int id);  // assign unique ids to all instructions<br>
> +  int  topologicalSort(SimpleArray<BasicBlock*>& Blocks, int ID);<br>
> +  int  topologicalFinalSort(SimpleArray<BasicBlock*>& Blocks, int ID);<br>
> +  void computeDominator();<br>
> +  void computePostDominator();<br>
> +<br>
> +private:<br>
> +  MemRegionRef Arena;        // The arena used to allocate this block.<br>
> +  SCFG         *CFGPtr;      // The CFG that contains this block.<br>
> +  int          BlockID : 31; // unique id for this BB in the containing CFG.<br>
> +                             // IDs are in topological order.<br>
> +  int          Visited : 1;  // Bit to determine if a block has been visited<br>
> +                             // during a traversal.<br>
> +  BlockArray  Predecessors;  // Predecessor blocks in the CFG.<br>
> +  InstrArray  Args;          // Phi nodes.  One argument per predecessor.<br>
> +  InstrArray  Instrs;        // Instructions.<br>
> +  Terminator* TermInstr;     // Terminating instruction<br>
> +<br>
> +  TopologyNode DominatorNode;       // The dominator tree<br>
> +  TopologyNode PostDominatorNode;   // The post-dominator tree<br>
>  };<br>
><br>
><br>
> -// An SCFG is a control-flow graph.  It consists of a set of basic blocks, each<br>
> -// of which terminates in a branch to another basic block.  There is one<br>
> -// entry point, and one exit point.<br>
> +/// An SCFG is a control-flow graph.  It consists of a set of basic blocks,<br>
> +/// each of which terminates in a branch to another basic block.  There is one<br>
> +/// entry point, and one exit point.<br>
>  class SCFG : public SExpr {<br>
>  public:<br>
>    typedef SimpleArray<BasicBlock *> BlockArray;<br>
> @@ -1568,20 +1694,29 @@ public:<br>
><br>
>    SCFG(MemRegionRef A, unsigned Nblocks)<br>
>      : SExpr(COP_SCFG), Arena(A), Blocks(A, Nblocks),<br>
> -      Entry(nullptr), Exit(nullptr) {<br>
> -    Entry = new (A) BasicBlock(A, nullptr);<br>
> -    Exit  = new (A) BasicBlock(A, Entry);<br>
> -    auto *V = new (A) Variable(new (A) Phi());<br>
> +      Entry(nullptr), Exit(nullptr), NumInstructions(0), Normal(false) {<br>
> +    Entry = new (A) BasicBlock(A);<br>
> +    Exit  = new (A) BasicBlock(A);<br>
> +    auto *V = new (A) Phi();<br>
>      Exit->addArgument(V);<br>
> +    Exit->setTerminator(new (A) Return(V));<br>
>      add(Entry);<br>
>      add(Exit);<br>
>    }<br>
>    SCFG(const SCFG &Cfg, BlockArray &&Ba) // steals memory from Ba<br>
>        : SExpr(COP_SCFG), Arena(Cfg.Arena), Blocks(std::move(Ba)),<br>
> -        Entry(nullptr), Exit(nullptr) {<br>
> +        Entry(nullptr), Exit(nullptr), NumInstructions(0), Normal(false) {<br>
>      // TODO: set entry and exit!<br>
>    }<br>
><br>
> +  /// Return true if this CFG is valid.<br>
> +  bool valid() const { return Entry && Exit && Blocks.size() > 0; }<br>
> +<br>
> +  /// Return true if this CFG has been normalized.<br>
> +  /// After normalization, blocks are in topological order, and block and<br>
> +  /// instruction IDs have been assigned.<br>
> +  bool normal() const { return Normal; }<br>
> +<br>
>    iterator begin() { return Blocks.begin(); }<br>
>    iterator end() { return Blocks.end(); }<br>
><br>
> @@ -1596,9 +1731,17 @@ public:<br>
>    const BasicBlock *exit() const { return Exit; }<br>
>    BasicBlock *exit() { return Exit; }<br>
><br>
> +  /// Return the number of blocks in the CFG.<br>
> +  /// Block::blockID() will return a number less than numBlocks();<br>
> +  size_t numBlocks() const { return Blocks.size(); }<br>
> +<br>
> +  /// Return the total number of instructions in the CFG.<br>
> +  /// This is useful for building instruction side-tables;<br>
> +  /// A call to SExpr::id() will return a number less than numInstructions().<br>
> +  unsigned numInstructions() { return NumInstructions; }<br>
> +<br>
>    inline void add(BasicBlock *BB) {<br>
> -    assert(BB->CFGPtr == nullptr || BB->CFGPtr == this);<br>
> -    BB->setBlockID(Blocks.size());<br>
> +    assert(BB->CFGPtr == nullptr);<br>
>      BB->CFGPtr = this;<br>
>      Blocks.reserveCheck(1, Arena);<br>
>      Blocks.push_back(BB);<br>
> @@ -1607,13 +1750,13 @@ public:<br>
>    void setEntry(BasicBlock *BB) { Entry = BB; }<br>
>    void setExit(BasicBlock *BB)  { Exit = BB;  }<br>
><br>
> -  // Set varable ids in all blocks.<br>
> -  void renumberVars();<br>
> +  void computeNormalForm();<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
>      Vs.enterCFG(*this);<br>
>      typename V::template Container<BasicBlock *> Bbs(Vs, Blocks.size());<br>
> +<br>
>      for (auto *B : Blocks) {<br>
>        Bbs.push_back( B->traverse(Vs, Vs.subExprCtx(Ctx)) );<br>
>      }<br>
> @@ -1623,101 +1766,26 @@ public:<br>
><br>
>    template <class C><br>
>    typename C::CType compare(const SCFG *E, C &Cmp) const {<br>
> -    // TODO -- implement CFG comparisons<br>
> +    // TODO: implement CFG comparisons<br>
>      return Cmp.comparePointers(this, E);<br>
>    }<br>
><br>
>  private:<br>
> +  void renumberInstrs();       // assign unique ids to all instructions<br>
> +<br>
> +private:<br>
>    MemRegionRef Arena;<br>
>    BlockArray   Blocks;<br>
>    BasicBlock   *Entry;<br>
>    BasicBlock   *Exit;<br>
> +  unsigned     NumInstructions;<br>
> +  bool         Normal;<br>
>  };<br>
><br>
><br>
> -class Goto : public SExpr {<br>
> -public:<br>
> -  static bool classof(const SExpr *E) { return E->opcode() == COP_Goto; }<br>
> -<br>
> -  Goto(BasicBlock *B, unsigned I)<br>
> -      : SExpr(COP_Goto), TargetBlock(B), Index(I) {}<br>
> -  Goto(const Goto &G, BasicBlock *B, unsigned I)<br>
> -      : SExpr(COP_Goto), TargetBlock(B), Index(I) {}<br>
> -<br>
> -  const BasicBlock *targetBlock() const { return TargetBlock; }<br>
> -  BasicBlock *targetBlock() { return TargetBlock; }<br>
> -<br>
> -  unsigned index() const { return Index; }<br>
> -<br>
> -  template <class V><br>
> -  typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> -    BasicBlock *Ntb = Vs.reduceBasicBlockRef(TargetBlock);<br>
> -    return Vs.reduceGoto(*this, Ntb);<br>
> -  }<br>
> -<br>
> -  template <class C><br>
> -  typename C::CType compare(const Goto *E, C &Cmp) const {<br>
> -    // TODO -- implement CFG comparisons<br>
> -    return Cmp.comparePointers(this, E);<br>
> -  }<br>
> -<br>
> -private:<br>
> -  BasicBlock *TargetBlock;<br>
> -  unsigned Index;   // Index into Phi nodes of target block.<br>
> -};<br>
> -<br>
> -<br>
> -class Branch : public SExpr {<br>
> -public:<br>
> -  static bool classof(const SExpr *E) { return E->opcode() == COP_Branch; }<br>
> -<br>
> -  Branch(SExpr *C, BasicBlock *T, BasicBlock *E, unsigned TI, unsigned EI)<br>
> -      : SExpr(COP_Branch), Condition(C), ThenBlock(T), ElseBlock(E),<br>
> -        ThenIndex(TI), ElseIndex(EI)<br>
> -  {}<br>
> -  Branch(const Branch &Br, SExpr *C, BasicBlock *T, BasicBlock *E,<br>
> -         unsigned TI, unsigned EI)<br>
> -      : SExpr(COP_Branch), Condition(C), ThenBlock(T), ElseBlock(E),<br>
> -        ThenIndex(TI), ElseIndex(EI)<br>
> -  {}<br>
> -<br>
> -  const SExpr *condition() const { return Condition; }<br>
> -  SExpr *condition() { return Condition; }<br>
> -<br>
> -  const BasicBlock *thenBlock() const { return ThenBlock; }<br>
> -  BasicBlock *thenBlock() { return ThenBlock; }<br>
> -<br>
> -  const BasicBlock *elseBlock() const { return ElseBlock; }<br>
> -  BasicBlock *elseBlock() { return ElseBlock; }<br>
> -<br>
> -  unsigned thenIndex() const { return ThenIndex; }<br>
> -  unsigned elseIndex() const { return ElseIndex; }<br>
> -<br>
> -  template <class V><br>
> -  typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> -    auto Nc = Vs.traverse(Condition, Vs.subExprCtx(Ctx));<br>
> -    BasicBlock *Ntb = Vs.reduceBasicBlockRef(ThenBlock);<br>
> -    BasicBlock *Nte = Vs.reduceBasicBlockRef(ElseBlock);<br>
> -    return Vs.reduceBranch(*this, Nc, Ntb, Nte);<br>
> -  }<br>
><br>
> -  template <class C><br>
> -  typename C::CType compare(const Branch *E, C &Cmp) const {<br>
> -    // TODO -- implement CFG comparisons<br>
> -    return Cmp.comparePointers(this, E);<br>
> -  }<br>
> -<br>
> -private:<br>
> -  SExpr *Condition;<br>
> -  BasicBlock *ThenBlock;<br>
> -  BasicBlock *ElseBlock;<br>
> -  unsigned ThenIndex;<br>
> -  unsigned ElseIndex;<br>
> -};<br>
> -<br>
> -<br>
> -// An identifier, e.g. 'foo' or 'x'.<br>
> -// This is a pseduo-term; it will be lowered to a variable or projection.<br>
> +/// An identifier, e.g. 'foo' or 'x'.<br>
> +/// This is a pseduo-term; it will be lowered to a variable or projection.<br>
>  class Identifier : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Identifier; }<br>
> @@ -1742,8 +1810,8 @@ private:<br>
>  };<br>
><br>
><br>
> -// An if-then-else expression.<br>
> -// This is a pseduo-term; it will be lowered to a branch in a CFG.<br>
> +/// An if-then-else expression.<br>
> +/// This is a pseduo-term; it will be lowered to a branch in a CFG.<br>
>  class IfThenElse : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_IfThenElse; }<br>
> @@ -1755,14 +1823,14 @@ public:<br>
>      : SExpr(I), Condition(C), ThenExpr(T), ElseExpr(E)<br>
>    { }<br>
><br>
> -  SExpr *condition() { return Condition.get(); }   // Address to store to<br>
> -  const SExpr *condition() const { return Condition.get(); }<br>
> +  SExpr *condition() { return Condition; }   // Address to store to<br>
> +  const SExpr *condition() const { return Condition; }<br>
><br>
> -  SExpr *thenExpr() { return ThenExpr.get(); }     // Value to store<br>
> -  const SExpr *thenExpr() const { return ThenExpr.get(); }<br>
> +  SExpr *thenExpr() { return ThenExpr; }     // Value to store<br>
> +  const SExpr *thenExpr() const { return ThenExpr; }<br>
><br>
> -  SExpr *elseExpr() { return ElseExpr.get(); }     // Value to store<br>
> -  const SExpr *elseExpr() const { return ElseExpr.get(); }<br>
> +  SExpr *elseExpr() { return ElseExpr; }     // Value to store<br>
> +  const SExpr *elseExpr() const { return ElseExpr; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -1784,14 +1852,14 @@ public:<br>
>    }<br>
><br>
>  private:<br>
> -  SExprRef Condition;<br>
> -  SExprRef ThenExpr;<br>
> -  SExprRef ElseExpr;<br>
> +  SExpr* Condition;<br>
> +  SExpr* ThenExpr;<br>
> +  SExpr* ElseExpr;<br>
>  };<br>
><br>
><br>
> -// A let-expression,  e.g.  let x=t; u.<br>
> -// This is a pseduo-term; it will be lowered to instructions in a CFG.<br>
> +/// A let-expression,  e.g.  let x=t; u.<br>
> +/// This is a pseduo-term; it will be lowered to instructions in a CFG.<br>
>  class Let : public SExpr {<br>
>  public:<br>
>    static bool classof(const SExpr *E) { return E->opcode() == COP_Let; }<br>
> @@ -1806,8 +1874,8 @@ public:<br>
>    Variable *variableDecl()  { return VarDecl; }<br>
>    const Variable *variableDecl() const { return VarDecl; }<br>
><br>
> -  SExpr *body() { return Body.get(); }<br>
> -  const SExpr *body() const { return Body.get(); }<br>
> +  SExpr *body() { return Body; }<br>
> +  const SExpr *body() const { return Body; }<br>
><br>
>    template <class V><br>
>    typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {<br>
> @@ -1834,14 +1902,14 @@ public:<br>
><br>
>  private:<br>
>    Variable *VarDecl;<br>
> -  SExprRef Body;<br>
> +  SExpr* Body;<br>
>  };<br>
><br>
><br>
><br>
>  const SExpr *getCanonicalVal(const SExpr *E);<br>
>  SExpr* simplifyToCanonicalVal(SExpr *E);<br>
> -void simplifyIncompleteArg(Variable *V, til::Phi *Ph);<br>
> +void simplifyIncompleteArg(til::Phi *Ph);<br>
><br>
><br>
>  } // end namespace til<br>
><br>
> Modified: cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h<br>
> URL: <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h?rev=217556&r1=217555&r2=217556&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h?rev=217556&r1=217555&r2=217556&view=diff</a><br>
> ==============================================================================<br>
> --- cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h (original)<br>
> +++ cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h Wed Sep 10 17:12:52 2014<br>
> @@ -58,11 +58,16 @@ public:<br>
>    // Traverse an expression -- returning a result of type R_SExpr.<br>
>    // Override this method to do something for every expression, regardless<br>
>    // of which kind it is.<br>
> -  typename R::R_SExpr traverse(SExprRef &E, typename R::R_Ctx Ctx) {<br>
> -    return traverse(E.get(), Ctx);<br>
> +  // E is a reference, so this can be use for in-place updates.<br>
> +  // The type T must be a subclass of SExpr.<br>
> +  template <class T><br>
> +  typename R::R_SExpr traverse(T* &E, typename R::R_Ctx Ctx) {<br>
> +    return traverseSExpr(E, Ctx);<br>
>    }<br>
><br>
> -  typename R::R_SExpr traverse(SExpr *E, typename R::R_Ctx Ctx) {<br>
> +  // Override this method to do something for every expression.<br>
> +  // Does not allow in-place updates.<br>
> +  typename R::R_SExpr traverseSExpr(SExpr *E, typename R::R_Ctx Ctx) {<br>
>      return traverseByCase(E, Ctx);<br>
>    }<br>
><br>
> @@ -75,6 +80,7 @@ public:<br>
>  #include "ThreadSafetyOps.def"<br>
>  #undef TIL_OPCODE_DEF<br>
>      }<br>
> +    return self()->reduceNull();<br>
>    }<br>
><br>
>  // Traverse e, by static dispatch on the type "X" of e.<br>
> @@ -92,10 +98,10 @@ public:<br>
>  class SimpleReducerBase {<br>
>  public:<br>
>    enum TraversalKind {<br>
> -    TRV_Normal,<br>
> -    TRV_Decl,<br>
> -    TRV_Lazy,<br>
> -    TRV_Type<br>
> +    TRV_Normal,   // ordinary subexpressions<br>
> +    TRV_Decl,     // declarations (e.g. function bodies)<br>
> +    TRV_Lazy,     // expressions that require lazy evaluation<br>
> +    TRV_Type      // type expressions<br>
>    };<br>
><br>
>    // R_Ctx defines a "context" for the traversal, which encodes information<br>
> @@ -147,153 +153,6 @@ protected:<br>
>  };<br>
><br>
><br>
> -// Implements a traversal that makes a deep copy of an SExpr.<br>
> -// The default behavior of reduce##X(...) is to create a copy of the original.<br>
> -// Subclasses can override reduce##X to implement non-destructive rewriting<br>
> -// passes.<br>
> -template<class Self><br>
> -class CopyReducer : public Traversal<Self, CopyReducerBase>,<br>
> -                    public CopyReducerBase {<br>
> -public:<br>
> -  CopyReducer(MemRegionRef A) : CopyReducerBase(A) {}<br>
> -<br>
> -public:<br>
> -  R_SExpr reduceNull() {<br>
> -    return nullptr;<br>
> -  }<br>
> -  // R_SExpr reduceFuture(...)  is never used.<br>
> -<br>
> -  R_SExpr reduceUndefined(Undefined &Orig) {<br>
> -    return new (Arena) Undefined(Orig);<br>
> -  }<br>
> -  R_SExpr reduceWildcard(Wildcard &Orig) {<br>
> -    return new (Arena) Wildcard(Orig);<br>
> -  }<br>
> -<br>
> -  R_SExpr reduceLiteral(Literal &Orig) {<br>
> -    return new (Arena) Literal(Orig);<br>
> -  }<br>
> -  template<class T><br>
> -  R_SExpr reduceLiteralT(LiteralT<T> &Orig) {<br>
> -    return new (Arena) LiteralT<T>(Orig);<br>
> -  }<br>
> -  R_SExpr reduceLiteralPtr(LiteralPtr &Orig) {<br>
> -    return new (Arena) LiteralPtr(Orig);<br>
> -  }<br>
> -<br>
> -  R_SExpr reduceFunction(Function &Orig, Variable *Nvd, R_SExpr E0) {<br>
> -    return new (Arena) Function(Orig, Nvd, E0);<br>
> -  }<br>
> -  R_SExpr reduceSFunction(SFunction &Orig, Variable *Nvd, R_SExpr E0) {<br>
> -    return new (Arena) SFunction(Orig, Nvd, E0);<br>
> -  }<br>
> -  R_SExpr reduceCode(Code &Orig, R_SExpr E0, R_SExpr E1) {<br>
> -    return new (Arena) Code(Orig, E0, E1);<br>
> -  }<br>
> -  R_SExpr reduceField(Field &Orig, R_SExpr E0, R_SExpr E1) {<br>
> -    return new (Arena) Field(Orig, E0, E1);<br>
> -  }<br>
> -<br>
> -  R_SExpr reduceApply(Apply &Orig, R_SExpr E0, R_SExpr E1) {<br>
> -    return new (Arena) Apply(Orig, E0, E1);<br>
> -  }<br>
> -  R_SExpr reduceSApply(SApply &Orig, R_SExpr E0, R_SExpr E1) {<br>
> -    return new (Arena) SApply(Orig, E0, E1);<br>
> -  }<br>
> -  R_SExpr reduceProject(Project &Orig, R_SExpr E0) {<br>
> -    return new (Arena) Project(Orig, E0);<br>
> -  }<br>
> -  R_SExpr reduceCall(Call &Orig, R_SExpr E0) {<br>
> -    return new (Arena) Call(Orig, E0);<br>
> -  }<br>
> -<br>
> -  R_SExpr reduceAlloc(Alloc &Orig, R_SExpr E0) {<br>
> -    return new (Arena) Alloc(Orig, E0);<br>
> -  }<br>
> -  R_SExpr reduceLoad(Load &Orig, R_SExpr E0) {<br>
> -    return new (Arena) Load(Orig, E0);<br>
> -  }<br>
> -  R_SExpr reduceStore(Store &Orig, R_SExpr E0, R_SExpr E1) {<br>
> -    return new (Arena) Store(Orig, E0, E1);<br>
> -  }<br>
> -  R_SExpr reduceArrayIndex(ArrayIndex &Orig, R_SExpr E0, R_SExpr E1) {<br>
> -    return new (Arena) ArrayIndex(Orig, E0, E1);<br>
> -  }<br>
> -  R_SExpr reduceArrayAdd(ArrayAdd &Orig, R_SExpr E0, R_SExpr E1) {<br>
> -    return new (Arena) ArrayAdd(Orig, E0, E1);<br>
> -  }<br>
> -  R_SExpr reduceUnaryOp(UnaryOp &Orig, R_SExpr E0) {<br>
> -    return new (Arena) UnaryOp(Orig, E0);<br>
> -  }<br>
> -  R_SExpr reduceBinaryOp(BinaryOp &Orig, R_SExpr E0, R_SExpr E1) {<br>
> -    return new (Arena) BinaryOp(Orig, E0, E1);<br>
> -  }<br>
> -  R_SExpr reduceCast(Cast &Orig, R_SExpr E0) {<br>
> -    return new (Arena) Cast(Orig, E0);<br>
> -  }<br>
> -<br>
> -  R_SExpr reduceSCFG(SCFG &Orig, Container<BasicBlock *> &Bbs) {<br>
> -    return nullptr;  // FIXME: implement CFG rewriting<br>
> -  }<br>
> -  R_BasicBlock reduceBasicBlock(BasicBlock &Orig, Container<Variable *> &As,<br>
> -                                Container<Variable *> &Is, R_SExpr T) {<br>
> -    return nullptr;  // FIXME: implement CFG rewriting<br>
> -  }<br>
> -  R_SExpr reducePhi(Phi &Orig, Container<R_SExpr> &As) {<br>
> -    return new (Arena) Phi(Orig, std::move(As.Elems));<br>
> -  }<br>
> -  R_SExpr reduceGoto(Goto &Orig, BasicBlock *B) {<br>
> -    return new (Arena) Goto(Orig, B, 0);  // FIXME: set index<br>
> -  }<br>
> -  R_SExpr reduceBranch(Branch &O, R_SExpr C, BasicBlock *B0, BasicBlock *B1) {<br>
> -    return new (Arena) Branch(O, C, B0, B1, 0, 0);  // FIXME: set indices<br>
> -  }<br>
> -<br>
> -  R_SExpr reduceIdentifier(Identifier &Orig) {<br>
> -    return new (Arena) Identifier(Orig);<br>
> -  }<br>
> -  R_SExpr reduceIfThenElse(IfThenElse &Orig, R_SExpr C, R_SExpr T, R_SExpr E) {<br>
> -    return new (Arena) IfThenElse(Orig, C, T, E);<br>
> -  }<br>
> -  R_SExpr reduceLet(Let &Orig, Variable *Nvd, R_SExpr B) {<br>
> -    return new (Arena) Let(Orig, Nvd, B);<br>
> -  }<br>
> -<br>
> -  // Create a new variable from orig, and push it onto the lexical scope.<br>
> -  Variable *enterScope(Variable &Orig, R_SExpr E0) {<br>
> -    return new (Arena) Variable(Orig, E0);<br>
> -  }<br>
> -  // Exit the lexical scope of orig.<br>
> -  void exitScope(const Variable &Orig) {}<br>
> -<br>
> -  void enterCFG(SCFG &Cfg) {}<br>
> -  void exitCFG(SCFG &Cfg) {}<br>
> -  void enterBasicBlock(BasicBlock &BB) {}<br>
> -  void exitBasicBlock(BasicBlock &BB) {}<br>
> -<br>
> -  // Map Variable references to their rewritten definitions.<br>
> -  Variable *reduceVariableRef(Variable *Ovd) { return Ovd; }<br>
> -<br>
> -  // Map BasicBlock references to their rewritten definitions.<br>
> -  BasicBlock *reduceBasicBlockRef(BasicBlock *Obb) { return Obb; }<br>
> -};<br>
> -<br>
> -<br>
> -class SExprCopier : public CopyReducer<SExprCopier> {<br>
> -public:<br>
> -  typedef SExpr *R_SExpr;<br>
> -<br>
> -  SExprCopier(MemRegionRef A) : CopyReducer(A) { }<br>
> -<br>
> -  // Create a copy of e in region a.<br>
> -  static SExpr *copy(SExpr *E, MemRegionRef A) {<br>
> -    SExprCopier Copier(A);<br>
> -    return Copier.traverse(E, TRV_Normal);<br>
> -  }<br>
> -};<br>
> -<br>
> -<br>
> -<br>
>  // Base class for visit traversals.<br>
>  class VisitReducerBase : public SimpleReducerBase {<br>
>  public:<br>
> @@ -368,8 +227,8 @@ public:<br>
>    R_SExpr reduceSCFG(SCFG &Orig, Container<BasicBlock *> Bbs) {<br>
>      return Bbs.Success;<br>
>    }<br>
> -  R_BasicBlock reduceBasicBlock(BasicBlock &Orig, Container<Variable *> &As,<br>
> -                                Container<Variable *> &Is, R_SExpr T) {<br>
> +  R_BasicBlock reduceBasicBlock(BasicBlock &Orig, Container<R_SExpr> &As,<br>
> +                                Container<R_SExpr> &Is, R_SExpr T) {<br>
>      return (As.Success && Is.Success && T);<br>
>    }<br>
>    R_SExpr reducePhi(Phi &Orig, Container<R_SExpr> &As) {<br>
> @@ -381,6 +240,9 @@ public:<br>
>    R_SExpr reduceBranch(Branch &O, R_SExpr C, BasicBlock *B0, BasicBlock *B1) {<br>
>      return C;<br>
>    }<br>
> +  R_SExpr reduceReturn(Return &O, R_SExpr E) {<br>
> +    return E;<br>
> +  }<br>
><br>
>    R_SExpr reduceIdentifier(Identifier &Orig) {<br>
>      return true;<br>
> @@ -433,7 +295,7 @@ public:<br>
>  #include "ThreadSafetyOps.def"<br>
>  #undef TIL_OPCODE_DEF<br>
>      }<br>
> -    llvm_unreachable("invalid enum");<br>
> +    return false;<br>
>    }<br>
>  };<br>
><br>
> @@ -514,9 +376,9 @@ public:<br>
><br>
><br>
><br>
> -inline std::ostream& operator<<(std::ostream& SS, llvm::StringRef R) {<br>
> -  return SS.write(R.data(), R.size());<br>
> -}<br>
> +// inline std::ostream& operator<<(std::ostream& SS, StringRef R) {<br>
> +//   return SS.write(R.data(), R.size());<br>
> +// }<br>
<br>
</div></div>The commented code I mentioned.<br>
<div class="HOEnZb"><div class="h5"><br>
><br>
>  // Pretty printer for TIL expressions<br>
>  template <typename Self, typename StreamType><br>
> @@ -587,6 +449,7 @@ protected:<br>
>        case COP_Phi:        return Prec_Atom;<br>
>        case COP_Goto:       return Prec_Atom;<br>
>        case COP_Branch:     return Prec_Atom;<br>
> +      case COP_Return:     return Prec_Other;<br>
><br>
>        case COP_Identifier: return Prec_Atom;<br>
>        case COP_IfThenElse: return Prec_Other;<br>
> @@ -595,22 +458,29 @@ protected:<br>
>      return Prec_MAX;<br>
>    }<br>
><br>
> -  void printBlockLabel(StreamType & SS, const BasicBlock *BB, unsigned index) {<br>
> +  void printBlockLabel(StreamType & SS, const BasicBlock *BB, int index) {<br>
>      if (!BB) {<br>
>        SS << "BB_null";<br>
>        return;<br>
>      }<br>
>      SS << "BB_";<br>
>      SS << BB->blockID();<br>
> -    SS << ":";<br>
> -    SS << index;<br>
> +    if (index >= 0) {<br>
> +      SS << ":";<br>
> +      SS << index;<br>
> +    }<br>
>    }<br>
><br>
> -  void printSExpr(const SExpr *E, StreamType &SS, unsigned P) {<br>
> +<br>
> +  void printSExpr(const SExpr *E, StreamType &SS, unsigned P, bool Sub=true) {<br>
>      if (!E) {<br>
>        self()->printNull(SS);<br>
>        return;<br>
>      }<br>
> +    if (Sub && E->block() && E->opcode() != COP_Variable) {<br>
> +      SS << "_x" << E->id();<br>
> +      return;<br>
> +    }<br>
>      if (self()->precedence(E) > P) {<br>
>        // Wrap expr in () if necessary.<br>
>        SS << "(";<br>
> @@ -740,20 +610,11 @@ protected:<br>
>      SS << E->clangDecl()->getNameAsString();<br>
>    }<br>
><br>
> -  void printVariable(const Variable *V, StreamType &SS, bool IsVarDecl = false) {<br>
> -    if (!IsVarDecl && Cleanup) {<br>
> -      const SExpr* E = getCanonicalVal(V);<br>
> -      if (E != V) {<br>
> -        printSExpr(E, SS, Prec_Atom);<br>
> -        return;<br>
> -      }<br>
> -    }<br>
> -    if (V->kind() == Variable::VK_LetBB)<br>
> -      SS << V->name() << V->getBlockID() << "_" << V->getID();<br>
> -    else if (CStyle && V->kind() == Variable::VK_SFun)<br>
> +  void printVariable(const Variable *V, StreamType &SS, bool IsVarDecl=false) {<br>
> +    if (CStyle && V->kind() == Variable::VK_SFun)<br>
>        SS << "this";<br>
>      else<br>
> -      SS << V->name() << V->getID();<br>
> +      SS << V->name() << V->id();<br>
>    }<br>
><br>
>    void printFunction(const Function *E, StreamType &SS, unsigned sugared = 0) {<br>
> @@ -927,32 +788,38 @@ protected:<br>
>      newline(SS);<br>
>    }<br>
><br>
> +<br>
> +  void printBBInstr(const SExpr *E, StreamType &SS) {<br>
> +    bool Sub = false;<br>
> +    if (E->opcode() == COP_Variable) {<br>
> +      auto *V = cast<Variable>(E);<br>
> +      SS << "let " << V->name() << V->id() << " = ";<br>
> +      E = V->definition();<br>
> +      Sub = true;<br>
> +    }<br>
> +    else if (E->opcode() != COP_Store) {<br>
> +      SS << "let _x" << E->id() << " = ";<br>
> +    }<br>
> +    self()->printSExpr(E, SS, Prec_MAX, Sub);<br>
> +    SS << ";";<br>
> +    newline(SS);<br>
> +  }<br>
> +<br>
>    void printBasicBlock(const BasicBlock *E, StreamType &SS) {<br>
>      SS << "BB_" << E->blockID() << ":";<br>
>      if (E->parent())<br>
>        SS << " BB_" << E->parent()->blockID();<br>
>      newline(SS);<br>
> -    for (auto *A : E->arguments()) {<br>
> -      SS << "let ";<br>
> -      self()->printVariable(A, SS, true);<br>
> -      SS << " = ";<br>
> -      self()->printSExpr(A->definition(), SS, Prec_MAX);<br>
> -      SS << ";";<br>
> -      newline(SS);<br>
> -    }<br>
> -    for (auto *I : E->instructions()) {<br>
> -      if (I->definition()->opcode() != COP_Store) {<br>
> -        SS << "let ";<br>
> -        self()->printVariable(I, SS, true);<br>
> -        SS << " = ";<br>
> -      }<br>
> -      self()->printSExpr(I->definition(), SS, Prec_MAX);<br>
> -      SS << ";";<br>
> -      newline(SS);<br>
> -    }<br>
> +<br>
> +    for (auto *A : E->arguments())<br>
> +      printBBInstr(A, SS);<br>
> +<br>
> +    for (auto *I : E->instructions())<br>
> +      printBBInstr(I, SS);<br>
> +<br>
>      const SExpr *T = E->terminator();<br>
>      if (T) {<br>
> -      self()->printSExpr(T, SS, Prec_MAX);<br>
> +      self()->printSExpr(T, SS, Prec_MAX, false);<br>
>        SS << ";";<br>
>        newline(SS);<br>
>      }<br>
> @@ -983,9 +850,14 @@ protected:<br>
>      SS << "branch (";<br>
>      self()->printSExpr(E->condition(), SS, Prec_MAX);<br>
>      SS << ") ";<br>
> -    printBlockLabel(SS, E->thenBlock(), E->thenIndex());<br>
> +    printBlockLabel(SS, E->thenBlock(), -1);<br>
>      SS << " ";<br>
> -    printBlockLabel(SS, E->elseBlock(), E->elseIndex());<br>
> +    printBlockLabel(SS, E->elseBlock(), -1);<br>
> +  }<br>
> +<br>
> +  void printReturn(const Return *E, StreamType &SS) {<br>
> +    SS << "return ";<br>
> +    self()->printSExpr(E->returnValue(), SS, Prec_Other);<br>
>    }<br>
><br>
>    void printIdentifier(const Identifier *E, StreamType &SS) {<br>
><br>
> Modified: cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyUtil.h<br>
> URL: <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyUtil.h?rev=217556&r1=217555&r2=217556&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyUtil.h?rev=217556&r1=217555&r2=217556&view=diff</a><br>
> ==============================================================================<br>
> --- cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyUtil.h (original)<br>
> +++ cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyUtil.h Wed Sep 10 17:12:52 2014<br>
> @@ -142,20 +142,35 @@ public:<br>
>      assert(i < Size && "Array index out of bounds.");<br>
>      return Data[i];<br>
>    }<br>
> +  T &back() {<br>
> +    assert(Size && "No elements in the array.");<br>
> +    return Data[Size - 1];<br>
> +  }<br>
> +  const T &back() const {<br>
> +    assert(Size && "No elements in the array.");<br>
> +    return Data[Size - 1];<br>
> +  }<br>
><br>
>    iterator begin() { return Data; }<br>
> +  iterator end()   { return Data + Size; }<br>
> +<br>
>    const_iterator begin() const { return Data; }<br>
> -  iterator end() { return Data + Size; }<br>
> -  const_iterator end() const { return Data + Size; }<br>
> +  const_iterator end()   const { return Data + Size; }<br>
><br>
>    const_iterator cbegin() const { return Data; }<br>
> -  const_iterator cend() const { return Data + Size; }<br>
> +  const_iterator cend()   const { return Data + Size; }<br>
><br>
>    void push_back(const T &Elem) {<br>
>      assert(Size < Capacity);<br>
>      Data[Size++] = Elem;<br>
>    }<br>
><br>
> +  // drop last n elements from array<br>
> +  void drop(unsigned n = 0) {<br>
> +    assert(Size > n);<br>
> +    Size -= n;<br>
> +  }<br>
> +<br>
>    void setValues(unsigned Sz, const T& C) {<br>
>      assert(Sz <= Capacity);<br>
>      Size = Sz;<br>
> @@ -173,6 +188,37 @@ public:<br>
>      return J - Osz;<br>
>    }<br>
><br>
> +  // An adaptor to reverse a simple array<br>
> +  class ReverseAdaptor {<br>
> +   public:<br>
> +    ReverseAdaptor(SimpleArray &Array) : Array(Array) {}<br>
> +    // A reverse iterator used by the reverse adaptor<br>
> +    class Iterator {<br>
> +     public:<br>
> +      Iterator(T *Data) : Data(Data) {}<br>
> +      T &operator*() { return *Data; }<br>
> +      const T &operator*() const { return *Data; }<br>
> +      Iterator &operator++() {<br>
> +        --Data;<br>
> +        return *this;<br>
> +      }<br>
> +      bool operator!=(Iterator Other) { return Data != Other.Data; }<br>
> +<br>
> +     private:<br>
> +      T *Data;<br>
> +    };<br>
> +    Iterator begin() { return Array.end() - 1; }<br>
> +    Iterator end() { return Array.begin() - 1; }<br>
> +    const Iterator begin() const { return Array.end() - 1; }<br>
> +    const Iterator end() const { return Array.begin() - 1; }<br>
> +<br>
> +   private:<br>
> +    SimpleArray &Array;<br>
> +  };<br>
> +<br>
> +  const ReverseAdaptor reverse() const { return ReverseAdaptor(*this); }<br>
> +  ReverseAdaptor reverse() { return ReverseAdaptor(*this); }<br>
> +<br>
>  private:<br>
>    // std::max is annoying here, because it requires a reference,<br>
>    // thus forcing InitialCapacity to be initialized outside the .h file.<br>
> @@ -187,6 +233,7 @@ private:<br>
>    size_t Capacity;<br>
>  };<br>
><br>
> +<br>
>  }  // end namespace til<br>
><br>
><br>
> @@ -312,6 +359,12 @@ private:<br>
>  };<br>
><br>
><br>
> +inline std::ostream& operator<<(std::ostream& ss, const StringRef str) {<br>
> +  ss << str.data();<br>
> +  return ss;<br>
> +}<br>
> +<br>
> +<br>
>  } // end namespace threadSafety<br>
>  } // end namespace clang<br>
><br>
><br>
> Modified: cfe/trunk/lib/Analysis/ThreadSafetyCommon.cpp<br>
> URL: <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/ThreadSafetyCommon.cpp?rev=217556&r1=217555&r2=217556&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/ThreadSafetyCommon.cpp?rev=217556&r1=217555&r2=217556&view=diff</a><br>
> ==============================================================================<br>
> --- cfe/trunk/lib/Analysis/ThreadSafetyCommon.cpp (original)<br>
> +++ cfe/trunk/lib/Analysis/ThreadSafetyCommon.cpp Wed Sep 10 17:12:52 2014<br>
> @@ -63,11 +63,9 @@ std::string getSourceLiteralString(const<br>
>  namespace til {<br>
><br>
>  // Return true if E is a variable that points to an incomplete Phi node.<br>
> -static bool isIncompleteVar(const SExpr *E) {<br>
> -  if (const auto *V = dyn_cast<Variable>(E)) {<br>
> -    if (const auto *Ph = dyn_cast<Phi>(V->definition()))<br>
> -      return Ph->status() == Phi::PH_Incomplete;<br>
> -  }<br>
> +static bool isIncompletePhi(const SExpr *E) {<br>
> +  if (const auto *Ph = dyn_cast<Phi>(E))<br>
> +    return Ph->status() == Phi::PH_Incomplete;<br>
>    return false;<br>
>  }<br>
><br>
> @@ -320,6 +318,8 @@ til::SExpr *SExprBuilder::translateCXXTh<br>
>  const ValueDecl *getValueDeclFromSExpr(const til::SExpr *E) {<br>
>    if (auto *V = dyn_cast<til::Variable>(E))<br>
>      return V->clangDecl();<br>
> +  if (auto *Ph = dyn_cast<til::Phi>(E))<br>
> +    return Ph->clangDecl();<br>
>    if (auto *P = dyn_cast<til::Project>(E))<br>
>      return P->clangDecl();<br>
>    if (auto *L = dyn_cast<til::LiteralPtr>(E))<br>
> @@ -641,14 +641,14 @@ SExprBuilder::translateDeclStmt(const De<br>
>  // If E is trivial returns E.<br>
>  til::SExpr *SExprBuilder::addStatement(til::SExpr* E, const Stmt *S,<br>
>                                         const ValueDecl *VD) {<br>
> -  if (!E || !CurrentBB || til::ThreadSafetyTIL::isTrivial(E))<br>
> +  if (!E || !CurrentBB || E->block() || til::ThreadSafetyTIL::isTrivial(E))<br>
>      return E;<br>
> -<br>
> -  til::Variable *V = new (Arena) til::Variable(E, VD);<br>
> -  CurrentInstructions.push_back(V);<br>
> +  if (VD)<br>
> +    E = new (Arena) til::Variable(E, VD);<br>
> +  CurrentInstructions.push_back(E);<br>
>    if (S)<br>
> -    insertStmt(S, V);<br>
> -  return V;<br>
> +    insertStmt(S, E);<br>
> +  return E;<br>
>  }<br>
><br>
><br>
> @@ -705,11 +705,11 @@ void SExprBuilder::makePhiNodeVar(unsign<br>
>    unsigned ArgIndex = CurrentBlockInfo->ProcessedPredecessors;<br>
>    assert(ArgIndex > 0 && ArgIndex < NPreds);<br>
><br>
> -  til::Variable *V = dyn_cast<til::Variable>(CurrentLVarMap[i].second);<br>
> -  if (V && V->getBlockID() == CurrentBB->blockID()) {<br>
> +  til::SExpr *CurrE = CurrentLVarMap[i].second;<br>
> +  if (CurrE->block() == CurrentBB) {<br>
>      // We already have a Phi node in the current block,<br>
>      // so just add the new variable to the Phi node.<br>
> -    til::Phi *Ph = dyn_cast<til::Phi>(V->definition());<br>
> +    til::Phi *Ph = dyn_cast<til::Phi>(CurrE);<br>
>      assert(Ph && "Expecting Phi node.");<br>
>      if (E)<br>
>        Ph->values()[ArgIndex] = E;<br>
> @@ -718,27 +718,26 @@ void SExprBuilder::makePhiNodeVar(unsign<br>
><br>
>    // Make a new phi node: phi(..., E)<br>
>    // All phi args up to the current index are set to the current value.<br>
> -  til::SExpr *CurrE = CurrentLVarMap[i].second;<br>
>    til::Phi *Ph = new (Arena) til::Phi(Arena, NPreds);<br>
>    Ph->values().setValues(NPreds, nullptr);<br>
>    for (unsigned PIdx = 0; PIdx < ArgIndex; ++PIdx)<br>
>      Ph->values()[PIdx] = CurrE;<br>
>    if (E)<br>
>      Ph->values()[ArgIndex] = E;<br>
> +  Ph->setClangDecl(CurrentLVarMap[i].first);<br>
>    // If E is from a back-edge, or either E or CurrE are incomplete, then<br>
>    // mark this node as incomplete; we may need to remove it later.<br>
> -  if (!E || isIncompleteVar(E) || isIncompleteVar(CurrE)) {<br>
> +  if (!E || isIncompletePhi(E) || isIncompletePhi(CurrE)) {<br>
>      Ph->setStatus(til::Phi::PH_Incomplete);<br>
>    }<br>
><br>
>    // Add Phi node to current block, and update CurrentLVarMap[i]<br>
> -  auto *Var = new (Arena) til::Variable(Ph, CurrentLVarMap[i].first);<br>
> -  CurrentArguments.push_back(Var);<br>
> +  CurrentArguments.push_back(Ph);<br>
>    if (Ph->status() == til::Phi::PH_Incomplete)<br>
> -    IncompleteArgs.push_back(Var);<br>
> +    IncompleteArgs.push_back(Ph);<br>
><br>
>    CurrentLVarMap.makeWritable();<br>
> -  CurrentLVarMap.elem(i).second = Var;<br>
> +  CurrentLVarMap.elem(i).second = Ph;<br>
>  }<br>
><br>
><br>
> @@ -812,15 +811,13 @@ void SExprBuilder::mergePhiNodesBackEdge<br>
>    unsigned ArgIndex = BBInfo[Blk->getBlockID()].ProcessedPredecessors;<br>
>    assert(ArgIndex > 0 && ArgIndex < BB->numPredecessors());<br>
><br>
> -  for (til::Variable *V : BB->arguments()) {<br>
> -    til::Phi *Ph = dyn_cast_or_null<til::Phi>(V->definition());<br>
> +  for (til::SExpr *PE : BB->arguments()) {<br>
> +    til::Phi *Ph = dyn_cast_or_null<til::Phi>(PE);<br>
>      assert(Ph && "Expecting Phi Node.");<br>
>      assert(Ph->values()[ArgIndex] == nullptr && "Wrong index for back edge.");<br>
> -    assert(V->clangDecl() && "No local variable for Phi node.");<br>
><br>
> -    til::SExpr *E = lookupVarDecl(V->clangDecl());<br>
> +    til::SExpr *E = lookupVarDecl(Ph->clangDecl());<br>
>      assert(E && "Couldn't find local variable for Phi node.");<br>
> -<br>
>      Ph->values()[ArgIndex] = E;<br>
>    }<br>
>  }<br>
> @@ -899,8 +896,8 @@ void SExprBuilder::enterCFGBlockBody(con<br>
>    // Push those arguments onto the basic block.<br>
>    CurrentBB->arguments().reserve(<br>
>      static_cast<unsigned>(CurrentArguments.size()), Arena);<br>
> -  for (auto *V : CurrentArguments)<br>
> -    CurrentBB->addArgument(V);<br>
> +  for (auto *A : CurrentArguments)<br>
> +    CurrentBB->addArgument(A);<br>
>  }<br>
><br>
><br>
> @@ -934,7 +931,7 @@ void SExprBuilder::exitCFGBlockBody(cons<br>
>      til::BasicBlock *BB = *It ? lookupBlock(*It) : nullptr;<br>
>      // TODO: set index<br>
>      unsigned Idx = BB ? BB->findPredecessorIndex(CurrentBB) : 0;<br>
> -    til::SExpr *Tm = new (Arena) til::Goto(BB, Idx);<br>
> +    auto *Tm = new (Arena) til::Goto(BB, Idx);<br>
>      CurrentBB->setTerminator(Tm);<br>
>    }<br>
>    else if (N == 2) {<br>
> @@ -942,9 +939,8 @@ void SExprBuilder::exitCFGBlockBody(cons<br>
>      til::BasicBlock *BB1 = *It ? lookupBlock(*It) : nullptr;<br>
>      ++It;<br>
>      til::BasicBlock *BB2 = *It ? lookupBlock(*It) : nullptr;<br>
> -    unsigned Idx1 = BB1 ? BB1->findPredecessorIndex(CurrentBB) : 0;<br>
> -    unsigned Idx2 = BB2 ? BB2->findPredecessorIndex(CurrentBB) : 0;<br>
> -    til::SExpr *Tm = new (Arena) til::Branch(C, BB1, BB2, Idx1, Idx2);<br>
> +    // FIXME: make sure these arent' critical edges.<br>
> +    auto *Tm = new (Arena) til::Branch(C, BB1, BB2);<br>
>      CurrentBB->setTerminator(Tm);<br>
>    }<br>
>  }<br>
> @@ -971,10 +967,9 @@ void SExprBuilder::exitCFGBlock(const CF<br>
><br>
><br>
>  void SExprBuilder::exitCFG(const CFGBlock *Last) {<br>
> -  for (auto *V : IncompleteArgs) {<br>
> -    til::Phi *Ph = dyn_cast<til::Phi>(V->definition());<br>
> -    if (Ph && Ph->status() == til::Phi::PH_Incomplete)<br>
> -      simplifyIncompleteArg(V, Ph);<br>
> +  for (auto *Ph : IncompleteArgs) {<br>
> +    if (Ph->status() == til::Phi::PH_Incomplete)<br>
> +      simplifyIncompleteArg(Ph);<br>
>    }<br>
><br>
>    CurrentArguments.clear();<br>
><br>
> Modified: cfe/trunk/lib/Analysis/ThreadSafetyTIL.cpp<br>
> URL: <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/ThreadSafetyTIL.cpp?rev=217556&r1=217555&r2=217556&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/ThreadSafetyTIL.cpp?rev=217556&r1=217555&r2=217556&view=diff</a><br>
> ==============================================================================<br>
> --- cfe/trunk/lib/Analysis/ThreadSafetyTIL.cpp (original)<br>
> +++ cfe/trunk/lib/Analysis/ThreadSafetyTIL.cpp Wed Sep 10 17:12:52 2014<br>
> @@ -48,12 +48,20 @@ StringRef getBinaryOpcodeString(TIL_Bina<br>
>  }<br>
><br>
><br>
> +SExpr* Future::force() {<br>
> +  Status = FS_evaluating;<br>
> +  Result = compute();<br>
> +  Status = FS_done;<br>
> +  return Result;<br>
> +}<br>
> +<br>
> +<br>
>  unsigned BasicBlock::addPredecessor(BasicBlock *Pred) {<br>
>    unsigned Idx = Predecessors.size();<br>
>    Predecessors.reserveCheck(1, Arena);<br>
>    Predecessors.push_back(Pred);<br>
> -  for (Variable *V : Args) {<br>
> -    if (Phi* Ph = dyn_cast<Phi>(V->definition())) {<br>
> +  for (SExpr *E : Args) {<br>
> +    if (Phi* Ph = dyn_cast<Phi>(E)) {<br>
>        Ph->values().reserveCheck(1, Arena);<br>
>        Ph->values().push_back(nullptr);<br>
>      }<br>
> @@ -61,105 +69,73 @@ unsigned BasicBlock::addPredecessor(Basi<br>
>    return Idx;<br>
>  }<br>
><br>
> +<br>
>  void BasicBlock::reservePredecessors(unsigned NumPreds) {<br>
>    Predecessors.reserve(NumPreds, Arena);<br>
> -  for (Variable *V : Args) {<br>
> -    if (Phi* Ph = dyn_cast<Phi>(V->definition())) {<br>
> +  for (SExpr *E : Args) {<br>
> +    if (Phi* Ph = dyn_cast<Phi>(E)) {<br>
>        Ph->values().reserve(NumPreds, Arena);<br>
>      }<br>
>    }<br>
>  }<br>
><br>
> -void BasicBlock::renumberVars() {<br>
> -  unsigned VID = 0;<br>
> -  for (Variable *V : Args) {<br>
> -    V->setID(BlockID, VID++);<br>
> -  }<br>
> -  for (Variable *V : Instrs) {<br>
> -    V->setID(BlockID, VID++);<br>
> -  }<br>
> -}<br>
> -<br>
> -void SCFG::renumberVars() {<br>
> -  for (BasicBlock *B : Blocks) {<br>
> -    B->renumberVars();<br>
> -  }<br>
> -}<br>
> -<br>
> -<br>
><br>
>  // If E is a variable, then trace back through any aliases or redundant<br>
>  // Phi nodes to find the canonical definition.<br>
>  const SExpr *getCanonicalVal(const SExpr *E) {<br>
> -  while (auto *V = dyn_cast<Variable>(E)) {<br>
> -    const SExpr *D;<br>
> -    do {<br>
> -      if (V->kind() != Variable::VK_Let)<br>
> -        return V;<br>
> -      D = V->definition();<br>
> -      auto *V2 = dyn_cast<Variable>(D);<br>
> -      if (V2)<br>
> -        V = V2;<br>
> -      else<br>
> -        break;<br>
> -    } while (true);<br>
> -<br>
> -    if (ThreadSafetyTIL::isTrivial(D))<br>
> -      return D;<br>
> -<br>
> -    if (const Phi *Ph = dyn_cast<Phi>(D)) {<br>
> +  while (true) {<br>
> +    if (auto *V = dyn_cast<Variable>(E)) {<br>
> +      if (V->kind() == Variable::VK_Let) {<br>
> +        E = V->definition();<br>
> +        continue;<br>
> +      }<br>
> +    }<br>
> +    if (const Phi *Ph = dyn_cast<Phi>(E)) {<br>
>        if (Ph->status() == Phi::PH_SingleVal) {<br>
>          E = Ph->values()[0];<br>
>          continue;<br>
>        }<br>
>      }<br>
> -    return V;<br>
> +    break;<br>
>    }<br>
>    return E;<br>
>  }<br>
><br>
><br>
> -<br>
>  // If E is a variable, then trace back through any aliases or redundant<br>
>  // Phi nodes to find the canonical definition.<br>
>  // The non-const version will simplify incomplete Phi nodes.<br>
>  SExpr *simplifyToCanonicalVal(SExpr *E) {<br>
> -  while (auto *V = dyn_cast<Variable>(E)) {<br>
> -    SExpr *D;<br>
> -    do {<br>
> +  while (true) {<br>
> +    if (auto *V = dyn_cast<Variable>(E)) {<br>
>        if (V->kind() != Variable::VK_Let)<br>
>          return V;<br>
> -      D = V->definition();<br>
> -      auto *V2 = dyn_cast<Variable>(D);<br>
> -      if (V2)<br>
> -        V = V2;<br>
> -      else<br>
> -        break;<br>
> -    } while (true);<br>
> -<br>
> -    if (ThreadSafetyTIL::isTrivial(D))<br>
> -      return D;<br>
> -<br>
> -    if (Phi *Ph = dyn_cast<Phi>(D)) {<br>
> +      // Eliminate redundant variables, e.g. x = y, or x = 5,<br>
> +      // but keep anything more complicated.<br>
> +      if (til::ThreadSafetyTIL::isTrivial(V->definition())) {<br>
> +        E = V->definition();<br>
> +        continue;<br>
> +      }<br>
> +      return V;<br>
> +    }<br>
> +    if (auto *Ph = dyn_cast<Phi>(E)) {<br>
>        if (Ph->status() == Phi::PH_Incomplete)<br>
> -        simplifyIncompleteArg(V, Ph);<br>
> -<br>
> +        simplifyIncompleteArg(Ph);<br>
> +      // Eliminate redundant Phi nodes.<br>
>        if (Ph->status() == Phi::PH_SingleVal) {<br>
>          E = Ph->values()[0];<br>
>          continue;<br>
>        }<br>
>      }<br>
> -    return V;<br>
> +    return E;<br>
>    }<br>
> -  return E;<br>
>  }<br>
><br>
><br>
> -<br>
>  // Trace the arguments of an incomplete Phi node to see if they have the same<br>
>  // canonical definition.  If so, mark the Phi node as redundant.<br>
>  // getCanonicalVal() will recursively call simplifyIncompletePhi().<br>
> -void simplifyIncompleteArg(Variable *V, til::Phi *Ph) {<br>
> +void simplifyIncompleteArg(til::Phi *Ph) {<br>
>    assert(Ph && Ph->status() == Phi::PH_Incomplete);<br>
><br>
>    // eliminate infinite recursion -- assume that this node is not redundant.<br>
> @@ -168,18 +144,200 @@ void simplifyIncompleteArg(Variable *V,<br>
>    SExpr *E0 = simplifyToCanonicalVal(Ph->values()[0]);<br>
>    for (unsigned i=1, n=Ph->values().size(); i<n; ++i) {<br>
>      SExpr *Ei = simplifyToCanonicalVal(Ph->values()[i]);<br>
> -    if (Ei == V)<br>
> +    if (Ei == Ph)<br>
>        continue;  // Recursive reference to itself.  Don't count.<br>
>      if (Ei != E0) {<br>
>        return;    // Status is already set to MultiVal.<br>
>      }<br>
>    }<br>
>    Ph->setStatus(Phi::PH_SingleVal);<br>
> -  // Eliminate Redundant Phi node.<br>
> -  V->setDefinition(Ph->values()[0]);<br>
>  }<br>
><br>
><br>
> +// Renumbers the arguments and instructions to have unique, sequential IDs.<br>
> +int BasicBlock::renumberInstrs(int ID) {<br>
> +  for (auto *Arg : Args)<br>
> +    Arg->setID(this, ID++);<br>
> +  for (auto *Instr : Instrs)<br>
> +    Instr->setID(this, ID++);<br>
> +  TermInstr->setID(this, ID++);<br>
> +  return ID;<br>
> +}<br>
> +<br>
> +// Sorts the CFGs blocks using a reverse post-order depth-first traversal.<br>
> +// Each block will be written into the Blocks array in order, and its BlockID<br>
> +// will be set to the index in the array.  Sorting should start from the entry<br>
> +// block, and ID should be the total number of blocks.<br>
> +int BasicBlock::topologicalSort(SimpleArray<BasicBlock*>& Blocks, int ID) {<br>
> +  if (Visited) return ID;<br>
> +  Visited = 1;<br>
> +  for (auto *Block : successors())<br>
> +    ID = Block->topologicalSort(Blocks, ID);<br>
> +  // set ID and update block array in place.<br>
> +  // We may lose pointers to unreachable blocks.<br>
> +  assert(ID > 0);<br>
> +  BlockID = --ID;<br>
> +  Blocks[BlockID] = this;<br>
> +  return ID;<br>
> +}<br>
> +<br>
> +// Performs a reverse topological traversal, starting from the exit block and<br>
> +// following back-edges.  The dominator is serialized before any predecessors,<br>
> +// which guarantees that all blocks are serialized after their dominator and<br>
> +// before their post-dominator (because it's a reverse topological traversal).<br>
> +// ID should be initially set to 0.<br>
> +//<br>
> +// This sort assumes that (1) dominators have been computed, (2) there are no<br>
> +// critical edges, and (3) the entry block is reachable from the exit block<br>
> +// and no blocks are accessable via traversal of back-edges from the exit that<br>
> +// weren't accessable via forward edges from the entry.<br>
> +int BasicBlock::topologicalFinalSort(SimpleArray<BasicBlock*>& Blocks, int ID) {<br>
> +  // Visited is assumed to have been set by the topologicalSort.  This pass<br>
> +  // assumes !Visited means that we've visited this node before.<br>
> +  if (!Visited) return ID;<br>
> +  Visited = 0;<br>
> +  if (DominatorNode.Parent)<br>
> +    ID = DominatorNode.Parent->topologicalFinalSort(Blocks, ID);<br>
> +  for (auto *Pred : Predecessors)<br>
> +    ID = Pred->topologicalFinalSort(Blocks, ID);<br>
> +  assert(ID < Blocks.size());<br>
> +  BlockID = ID++;<br>
> +  Blocks[BlockID] = this;<br>
> +  return ID;<br>
> +}<br>
> +<br>
> +// Computes the immediate dominator of the current block.  Assumes that all of<br>
> +// its predecessors have already computed their dominators.  This is achieved<br>
> +// by visiting the nodes in topological order.<br>
> +void BasicBlock::computeDominator() {<br>
> +  BasicBlock *Candidate = nullptr;<br>
> +  // Walk backwards from each predecessor to find the common dominator node.<br>
> +  for (auto *Pred : Predecessors) {<br>
> +    // Skip back-edges<br>
> +    if (Pred->BlockID >= BlockID) continue;<br>
> +    // If we don't yet have a candidate for dominator yet, take this one.<br>
> +    if (Candidate == nullptr) {<br>
> +      Candidate = Pred;<br>
> +      continue;<br>
> +    }<br>
> +    // Walk the alternate and current candidate back to find a common ancestor.<br>
> +    auto *Alternate = Pred;<br>
> +    while (Alternate != Candidate) {<br>
> +      if (Candidate->BlockID > Alternate->BlockID)<br>
> +        Candidate = Candidate->DominatorNode.Parent;<br>
> +      else<br>
> +        Alternate = Alternate->DominatorNode.Parent;<br>
> +    }<br>
> +  }<br>
> +  DominatorNode.Parent = Candidate;<br>
> +  DominatorNode.SizeOfSubTree = 1;<br>
> +}<br>
> +<br>
> +// Computes the immediate post-dominator of the current block.  Assumes that all<br>
> +// of its successors have already computed their post-dominators.  This is<br>
> +// achieved visiting the nodes in reverse topological order.<br>
> +void BasicBlock::computePostDominator() {<br>
> +  BasicBlock *Candidate = nullptr;<br>
> +  // Walk back from each predecessor to find the common post-dominator node.<br>
> +  for (auto *Succ : successors()) {<br>
> +    // Skip back-edges<br>
> +    if (Succ->BlockID <= BlockID) continue;<br>
> +    // If we don't yet have a candidate for post-dominator yet, take this one.<br>
> +    if (Candidate == nullptr) {<br>
> +      Candidate = Succ;<br>
> +      continue;<br>
> +    }<br>
> +    // Walk the alternate and current candidate back to find a common ancestor.<br>
> +    auto *Alternate = Succ;<br>
> +    while (Alternate != Candidate) {<br>
> +      if (Candidate->BlockID < Alternate->BlockID)<br>
> +        Candidate = Candidate->PostDominatorNode.Parent;<br>
> +      else<br>
> +        Alternate = Alternate->PostDominatorNode.Parent;<br>
> +    }<br>
> +  }<br>
> +  PostDominatorNode.Parent = Candidate;<br>
> +  PostDominatorNode.SizeOfSubTree = 1;<br>
> +}<br>
> +<br>
> +<br>
> +// Renumber instructions in all blocks<br>
> +void SCFG::renumberInstrs() {<br>
> +  int InstrID = 0;<br>
> +  for (auto *Block : Blocks)<br>
> +    InstrID = Block->renumberInstrs(InstrID);<br>
> +}<br>
> +<br>
> +<br>
> +static inline void computeNodeSize(BasicBlock *B,<br>
> +                                   BasicBlock::TopologyNode BasicBlock::*TN) {<br>
> +  BasicBlock::TopologyNode *N = &(B->*TN);<br>
> +  if (N->Parent) {<br>
> +    BasicBlock::TopologyNode *P = &(N->Parent->*TN);<br>
> +    // Initially set ID relative to the (as yet uncomputed) parent ID<br>
> +    N->NodeID = P->SizeOfSubTree;<br>
> +    P->SizeOfSubTree += N->SizeOfSubTree;<br>
> +  }<br>
> +}<br>
> +<br>
> +static inline void computeNodeID(BasicBlock *B,<br>
> +                                 BasicBlock::TopologyNode BasicBlock::*TN) {<br>
> +  BasicBlock::TopologyNode *N = &(B->*TN);<br>
> +  if (N->Parent) {<br>
> +    BasicBlock::TopologyNode *P = &(N->Parent->*TN);<br>
> +    N->NodeID += P->NodeID;    // Fix NodeIDs relative to starting node.<br>
> +  }<br>
> +}<br>
> +<br>
> +<br>
> +// Normalizes a CFG.  Normalization has a few major components:<br>
> +// 1) Removing unreachable blocks.<br>
> +// 2) Computing dominators and post-dominators<br>
> +// 3) Topologically sorting the blocks into the "Blocks" array.<br>
> +void SCFG::computeNormalForm() {<br>
> +  // Topologically sort the blocks starting from the entry block.<br>
> +  int NumUnreachableBlocks = Entry->topologicalSort(Blocks, Blocks.size());<br>
> +  if (NumUnreachableBlocks > 0) {<br>
> +    // If there were unreachable blocks shift everything down, and delete them.<br>
> +    for (size_t I = NumUnreachableBlocks, E = Blocks.size(); I < E; ++I) {<br>
> +      size_t NI = I - NumUnreachableBlocks;<br>
> +      Blocks[NI] = Blocks[I];<br>
> +      Blocks[NI]->BlockID = NI;<br>
> +      // FIXME: clean up predecessor pointers to unreachable blocks?<br>
> +    }<br>
> +    Blocks.drop(NumUnreachableBlocks);<br>
> +  }<br>
> +<br>
> +  // Compute dominators.<br>
> +  for (auto *Block : Blocks)<br>
> +    Block->computeDominator();<br>
> +<br>
> +  // Once dominators have been computed, the final sort may be performed.<br>
> +  int NumBlocks = Exit->topologicalFinalSort(Blocks, 0);<br>
> +  assert(NumBlocks == Blocks.size());<br>
> +  (void) NumBlocks;<br>
> +<br>
> +  // Renumber the instructions now that we have a final sort.<br>
> +  renumberInstrs();<br>
> +<br>
> +  // Compute post-dominators and compute the sizes of each node in the<br>
> +  // dominator tree.<br>
> +  for (auto *Block : Blocks.reverse()) {<br>
> +    Block->computePostDominator();<br>
> +    computeNodeSize(Block, &BasicBlock::DominatorNode);<br>
> +  }<br>
> +  // Compute the sizes of each node in the post-dominator tree and assign IDs in<br>
> +  // the dominator tree.<br>
> +  for (auto *Block : Blocks) {<br>
> +    computeNodeID(Block, &BasicBlock::DominatorNode);<br>
> +    computeNodeSize(Block, &BasicBlock::PostDominatorNode);<br>
> +  }<br>
> +  // Assign IDs in the post-dominator tree.<br>
> +  for (auto *Block : Blocks.reverse()) {<br>
> +    computeNodeID(Block, &BasicBlock::PostDominatorNode);<br>
> +  }<br>
> +}<br>
> +<br>
>  }  // end namespace til<br>
>  }  // end namespace threadSafety<br>
>  }  // end namespace clang<br>
><br>
><br>
> _______________________________________________<br>
> cfe-commits mailing list<br>
> <a href="mailto:cfe-commits@cs.uiuc.edu">cfe-commits@cs.uiuc.edu</a><br>
> <a href="http://lists.cs.uiuc.edu/mailman/listinfo/cfe-commits" target="_blank">http://lists.cs.uiuc.edu/mailman/listinfo/cfe-commits</a><br>
</div></div></blockquote></div><br><br clear="all"><div><br></div>-- <br>DeLesley Hutchins | Software Engineer | <a href="mailto:delesley@google.com" target="_blank">delesley@google.com</a> | 505-206-0315<br>
</div>