title: How to emulate thread_local in llvm-ir?
body: <p>The following code is currently does not work in lli:</p>
  
  <pre><code>//main.cpp 
  extern thread_local int tls;
  int main() {
      tls = 42;
      return 0;
  }
  
  //clang++ -S -emit-llvm main.cpp &amp;&amp; lli main.ll
  </code></pre>
  
  <p>llvm-ir:</p>
  
  <pre><code>; ModuleID = 'main.cpp'
  target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
  target triple = "x86_64-pc-linux-gnu"
  
  @tls = external thread_local global i32, align 4
  
  ; Function Attrs: norecurse uwtable
  define i32 @main() #0 {
    %1 = alloca i32, align 4
    store i32 0, i32* %1, align 4
    %2 = call i32* @_ZTW3tls()
    store i32 42, i32* %2, align 4
    ret i32 0
  }
  
  define weak_odr hidden i32* @_ZTW3tls() {
    br i1 icmp ne (void ()* @_ZTH3tls, void ()* null), label %1, label %2
  
  ; &lt;label&gt;:1                                       ; preds = %0
    call void @_ZTH3tls()
    br label %2
  
  ; &lt;label&gt;:2                                       ; preds = %1, %0
    ret i32* @tls
  }
  
  declare extern_weak void @_ZTH3tls()
  </code></pre>
  
  <p>It causes the following error:</p>
  
  <pre><code>LLVM ERROR: Cannot select: 0x55ec0e9c3a60: i64 = X86ISD::WrapperRIP 
  TargetGlobalTLSAddress:i64&lt;i32* @tls&gt; 0 [TF=10]
     0x55ec0e9c3858: i64 = TargetGlobalTLSAddress&lt;i32* @tls&gt; 0 [TF=10]
  In function: _ZTW3tls
  </code></pre>
  
  <p>Is there a way to emulate TLS and transform the llvm-ir to make this work ?</p>
  
  <p>Would it be feasible to use a global map from thread_id to pointers and replace every occurrence of thread-local with allocator/deallocator/getter/setter ?</p>
  
  <p>Are <code>-femulated-tls</code> and <code>-ftls-model</code> of any use ?</p>
  
  <p>related questions:</p>
  
  <p><a href="https://stackoverflow.com/questions/42163796/how-to-perform-targetlowering-in-a-ir-trasformation-pass?noredirect=1&amp;lq=1">how to perform TargetLowering in a IR-trasformation pass?</a></p>
  
  <p><a href="http://lists.llvm.org/pipermail/llvm-dev/2017-February/109947.html" rel="nofollow noreferrer">http://lists.llvm.org/pipermail/llvm-dev/2017-February/109947.html</a></p>