Privatize the ConstantFP table. I'm on a roll!
[oota-llvm.git] / lib / VMCore / LLVMContextImpl.cpp
1 //===--------------- LLVMContextImpl.cpp - Implementation ------*- C++ -*--===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements LLVMContextImpl, the opaque implementation 
11 //  of LLVMContext.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "LLVMContextImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/LLVMContext.h"
19 using namespace llvm;
20
21 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 
22 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
23 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
24 // compare APInt's of different widths, which would violate an APInt class
25 // invariant which generates an assertion.
26 ConstantInt *LLVMContextImpl::getConstantInt(const APInt& V) {
27   // Get the corresponding integer type for the bit width of the value.
28   const IntegerType *ITy = Context.getIntegerType(V.getBitWidth());
29   // get an existing value or the insertion position
30   DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
31   
32   ConstantsLock.reader_acquire();
33   ConstantInt *&Slot = IntConstants[Key]; 
34   ConstantsLock.reader_release();
35     
36   if (!Slot) {
37     sys::SmartScopedWriter<true> Writer(ConstantsLock);
38     ConstantInt *&NewSlot = IntConstants[Key]; 
39     if (!Slot) {
40       NewSlot = new ConstantInt(ITy, V);
41     }
42     
43     return NewSlot;
44   } else {
45     return Slot;
46   }
47 }
48
49 ConstantFP *LLVMContextImpl::getConstantFP(const APFloat &V) {
50   DenseMapAPFloatKeyInfo::KeyTy Key(V);
51   
52   ConstantsLock.reader_acquire();
53   ConstantFP *&Slot = FPConstants[Key];
54   ConstantsLock.reader_release();
55     
56   if (!Slot) {
57     sys::SmartScopedWriter<true> Writer(ConstantsLock);
58     ConstantFP *&NewSlot = FPConstants[Key];
59     if (!NewSlot) {
60       const Type *Ty;
61       if (&V.getSemantics() == &APFloat::IEEEsingle)
62         Ty = Type::FloatTy;
63       else if (&V.getSemantics() == &APFloat::IEEEdouble)
64         Ty = Type::DoubleTy;
65       else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
66         Ty = Type::X86_FP80Ty;
67       else if (&V.getSemantics() == &APFloat::IEEEquad)
68         Ty = Type::FP128Ty;
69       else {
70         assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 
71                "Unknown FP format");
72         Ty = Type::PPC_FP128Ty;
73       }
74       NewSlot = new ConstantFP(Ty, V);
75     }
76     
77     return NewSlot;
78   }
79   
80   return Slot;
81 }