blob: 6e4cbe54240331dc21d234ff48ef014a61ef18f7 [file] [log] [blame]
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- 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 is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "asan"
17
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +000018#include "BlackList.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000019#include "llvm/Function.h"
20#include "llvm/IRBuilder.h"
Kostya Serebryanyf7b08222012-07-20 09:54:50 +000021#include "llvm/InlineAsm.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000022#include "llvm/IntrinsicInst.h"
23#include "llvm/LLVMContext.h"
24#include "llvm/Module.h"
25#include "llvm/Type.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000026#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/SmallSet.h"
29#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000032#include "llvm/ADT/Triple.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/DataTypes.h"
35#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000036#include "llvm/Support/raw_ostream.h"
37#include "llvm/Support/system_error.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000038#include "llvm/DataLayout.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000039#include "llvm/Target/TargetMachine.h"
40#include "llvm/Transforms/Instrumentation.h"
41#include "llvm/Transforms/Utils/BasicBlockUtils.h"
42#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000043
44#include <string>
45#include <algorithm>
46
47using namespace llvm;
48
49static const uint64_t kDefaultShadowScale = 3;
50static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
51static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000052static const uint64_t kDefaultShadowOffsetAndroid = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000053
54static const size_t kMaxStackMallocSize = 1 << 16; // 64K
55static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
56static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
57
58static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000059static const char *kAsanModuleDtorName = "asan.module_dtor";
60static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000061static const char *kAsanReportErrorTemplate = "__asan_report_";
62static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000063static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000064static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
65static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000066static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000067static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000068static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
69static const char *kAsanMappingScaleName = "__asan_mapping_scale";
70static const char *kAsanStackMallocName = "__asan_stack_malloc";
71static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000072static const char *kAsanGenPrefix = "__asan_gen_";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000073
74static const int kAsanStackLeftRedzoneMagic = 0xf1;
75static const int kAsanStackMidRedzoneMagic = 0xf2;
76static const int kAsanStackRightRedzoneMagic = 0xf3;
77static const int kAsanStackPartialRedzoneMagic = 0xf4;
78
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000079// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
80static const size_t kNumberOfAccessSizes = 5;
81
Kostya Serebryany800e03f2011-11-16 01:35:23 +000082// Command-line flags.
83
84// This flag may need to be replaced with -f[no-]asan-reads.
85static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
86 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
87static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
88 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000089static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
90 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
91 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +000092static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
93 cl::desc("use instrumentation with slow path for all accesses"),
94 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000095// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +000096// in any given BB. Normally, this should be set to unlimited (INT_MAX),
97// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
98// set it to 10000.
99static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
100 cl::init(10000),
101 cl::desc("maximal number of instructions to instrument in any given BB"),
102 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000103// This flag may need to be replaced with -f[no]asan-stack.
104static cl::opt<bool> ClStack("asan-stack",
105 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
106// This flag may need to be replaced with -f[no]asan-use-after-return.
107static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
108 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
109// This flag may need to be replaced with -f[no]asan-globals.
110static cl::opt<bool> ClGlobals("asan-globals",
111 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000112static cl::opt<bool> ClInitializers("asan-initialization-order",
113 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000114static cl::opt<bool> ClMemIntrin("asan-memintrin",
115 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
116// This flag may need to be replaced with -fasan-blacklist.
117static cl::opt<std::string> ClBlackListFile("asan-blacklist",
118 cl::desc("File containing the list of functions to ignore "
119 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000120
121// These flags allow to change the shadow mapping.
122// The shadow mapping looks like
123// Shadow = (Mem >> scale) + (1 << offset_log)
124static cl::opt<int> ClMappingScale("asan-mapping-scale",
125 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
126static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
127 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
128
129// Optimization flags. Not user visible, used mostly for testing
130// and benchmarking the tool.
131static cl::opt<bool> ClOpt("asan-opt",
132 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
133static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
134 cl::desc("Instrument the same temp just once"), cl::Hidden,
135 cl::init(true));
136static cl::opt<bool> ClOptGlobals("asan-opt-globals",
137 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
138
139// Debug flags.
140static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
141 cl::init(0));
142static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
143 cl::Hidden, cl::init(0));
144static cl::opt<std::string> ClDebugFunc("asan-debug-func",
145 cl::Hidden, cl::desc("Debug func"));
146static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
147 cl::Hidden, cl::init(-1));
148static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
149 cl::Hidden, cl::init(-1));
150
151namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000152/// A set of dynamically initialized globals extracted from metadata.
153class SetOfDynamicallyInitializedGlobals {
154 public:
155 void Init(Module& M) {
156 // Clang generates metadata identifying all dynamically initialized globals.
157 NamedMDNode *DynamicGlobals =
158 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
159 if (!DynamicGlobals)
160 return;
161 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
162 MDNode *MDN = DynamicGlobals->getOperand(i);
163 assert(MDN->getNumOperands() == 1);
164 Value *VG = MDN->getOperand(0);
165 // The optimizer may optimize away a global entirely, in which case we
166 // cannot instrument access to it.
167 if (!VG)
168 continue;
169 DynInitGlobals.insert(cast<GlobalVariable>(VG));
170 }
171 }
172 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
173 private:
174 SmallSet<GlobalValue*, 32> DynInitGlobals;
175};
176
177
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000178/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000179struct AddressSanitizer : public FunctionPass {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000180 AddressSanitizer();
Alexander Potapenko25878042012-01-23 11:22:43 +0000181 virtual const char *getPassName() const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000182 void instrumentMop(Instruction *I);
183 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000184 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000185 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
186 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000187 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000188 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000189 bool instrumentMemIntrinsic(MemIntrinsic *MI);
190 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000191 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000192 Instruction *InsertBefore, bool IsWrite);
193 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000194 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000195 void createInitializerPoisonCalls(Module &M,
196 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000197 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000198 bool poisonStackInFunction(Function &F);
199 virtual bool doInitialization(Module &M);
200 virtual bool doFinalization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000201 bool insertGlobalRedzones(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000202 static char ID; // Pass identification, replacement for typeid
203
204 private:
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000205 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
206 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanovd8313be2012-03-02 10:41:08 +0000207 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000208 return SizeInBytes;
209 }
210 uint64_t getAlignedSize(uint64_t SizeInBytes) {
211 return ((SizeInBytes + RedzoneSize - 1)
212 / RedzoneSize) * RedzoneSize;
213 }
214 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
215 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
216 return getAlignedSize(SizeInBytes);
217 }
218
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000219 Function *checkInterfaceFunction(Constant *FuncOrBitcast);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000220 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000221 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
222 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000223 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000224 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000225
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000226 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000227 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000228 uint64_t MappingOffset;
229 int MappingScale;
230 size_t RedzoneSize;
231 int LongSize;
232 Type *IntptrTy;
233 Type *IntptrPtrTy;
234 Function *AsanCtorFunction;
235 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000236 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
237 Function *AsanHandleNoReturnFunc;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000238 Instruction *CtorInsertBefore;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000239 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000240 // This array is indexed by AccessIsWrite and log2(AccessSize).
241 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000242 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000243 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000244};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000245
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000246} // namespace
247
248char AddressSanitizer::ID = 0;
249INITIALIZE_PASS(AddressSanitizer, "asan",
250 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
251 false, false)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000252AddressSanitizer::AddressSanitizer() : FunctionPass(ID) { }
253FunctionPass *llvm::createAddressSanitizerPass() {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000254 return new AddressSanitizer();
255}
256
Alexander Potapenko25878042012-01-23 11:22:43 +0000257const char *AddressSanitizer::getPassName() const {
258 return "AddressSanitizer";
259}
260
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000261static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
262 size_t Res = CountTrailingZeros_32(TypeSize / 8);
263 assert(Res < kNumberOfAccessSizes);
264 return Res;
265}
266
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000267// Create a constant for Str so that we can pass it to the run-time lib.
268static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000269 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000270 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000271 GlobalValue::PrivateLinkage, StrConst,
272 kAsanGenPrefix);
273}
274
275static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
276 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000277}
278
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000279Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
280 // Shadow >> scale
281 Shadow = IRB.CreateLShr(Shadow, MappingScale);
282 if (MappingOffset == 0)
283 return Shadow;
284 // (Shadow >> scale) | offset
285 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
286 MappingOffset));
287}
288
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000289void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000290 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000291 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
292 // Check the first byte.
293 {
294 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000295 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000296 }
297 // Check the last byte.
298 {
299 IRBuilder<> IRB(InsertBefore);
300 Value *SizeMinusOne = IRB.CreateSub(
301 Size, ConstantInt::get(Size->getType(), 1));
302 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
303 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
304 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000305 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000306 }
307}
308
309// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000310bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000311 Value *Dst = MI->getDest();
312 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000313 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000314 Value *Length = MI->getLength();
315
316 Constant *ConstLength = dyn_cast<Constant>(Length);
317 Instruction *InsertBefore = MI;
318 if (ConstLength) {
319 if (ConstLength->isNullValue()) return false;
320 } else {
321 // The size is not a constant so it could be zero -- check at run-time.
322 IRBuilder<> IRB(InsertBefore);
323
324 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000325 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000326 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000327 }
328
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000329 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000330 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000331 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000332 return true;
333}
334
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000335// If I is an interesting memory access, return the PointerOperand
336// and set IsWrite. Otherwise return NULL.
337static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000338 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000339 if (!ClInstrumentReads) return NULL;
340 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000341 return LI->getPointerOperand();
342 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000343 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
344 if (!ClInstrumentWrites) return NULL;
345 *IsWrite = true;
346 return SI->getPointerOperand();
347 }
348 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
349 if (!ClInstrumentAtomics) return NULL;
350 *IsWrite = true;
351 return RMW->getPointerOperand();
352 }
353 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
354 if (!ClInstrumentAtomics) return NULL;
355 *IsWrite = true;
356 return XCHG->getPointerOperand();
357 }
358 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000359}
360
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000361void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000362 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000363 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
364 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000365 if (ClOpt && ClOptGlobals) {
366 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
367 // If initialization order checking is disabled, a simple access to a
368 // dynamically initialized global is always valid.
369 if (!ClInitializers)
370 return;
371 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000372 // have to instrument it. However, if a global does not have initailizer
373 // at all, we assume it has dynamic initializer (in other TU).
374 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000375 return;
376 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000377 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000378
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000379 Type *OrigPtrTy = Addr->getType();
380 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
381
382 assert(OrigTy->isSized());
383 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
384
385 if (TypeSize != 8 && TypeSize != 16 &&
386 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
387 // Ignore all unusual sizes.
388 return;
389 }
390
391 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000392 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000393}
394
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000395// Validate the result of Module::getOrInsertFunction called for an interface
396// function of AddressSanitizer. If the instrumented module defines a function
397// with the same name, their prototypes must match, otherwise
398// getOrInsertFunction returns a bitcast.
399Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
400 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
401 FuncOrBitcast->dump();
402 report_fatal_error("trying to redefine an AddressSanitizer "
403 "interface function");
404}
405
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000406Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000407 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000408 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000409 IRBuilder<> IRB(InsertBefore);
410 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
411 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000412 // We don't do Call->setDoesNotReturn() because the BB already has
413 // UnreachableInst at the end.
414 // This EmptyAsm is required to avoid callback merge.
415 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000416 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000417}
418
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000419Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000420 Value *ShadowValue,
421 uint32_t TypeSize) {
422 size_t Granularity = 1 << MappingScale;
423 // Addr & (Granularity - 1)
424 Value *LastAccessedByte = IRB.CreateAnd(
425 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
426 // (Addr & (Granularity - 1)) + size - 1
427 if (TypeSize / 8 > 1)
428 LastAccessedByte = IRB.CreateAdd(
429 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
430 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
431 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000432 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000433 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
434 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
435}
436
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000437void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000438 IRBuilder<> &IRB, Value *Addr,
439 uint32_t TypeSize, bool IsWrite) {
440 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
441
442 Type *ShadowTy = IntegerType::get(
443 *C, std::max(8U, TypeSize >> MappingScale));
444 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
445 Value *ShadowPtr = memToShadow(AddrLong, IRB);
446 Value *CmpVal = Constant::getNullValue(ShadowTy);
447 Value *ShadowValue = IRB.CreateLoad(
448 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
449
450 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000451 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000452 size_t Granularity = 1 << MappingScale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000453 TerminatorInst *CrashTerm = 0;
454
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000455 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000456 TerminatorInst *CheckTerm =
457 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000458 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000459 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000460 IRB.SetInsertPoint(CheckTerm);
461 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000462 BasicBlock *CrashBlock =
463 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000464 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000465 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
466 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000467 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000468 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000469 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000470
471 Instruction *Crash =
472 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
473 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000474}
475
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000476void AddressSanitizer::createInitializerPoisonCalls(Module &M,
477 Value *FirstAddr,
478 Value *LastAddr) {
479 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
480 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
481 // If that function is not present, this TU contains no globals, or they have
482 // all been optimized away
483 if (!GlobalInit)
484 return;
485
486 // Set up the arguments to our poison/unpoison functions.
487 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
488
489 // Declare our poisoning and unpoisoning functions.
490 Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
491 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
492 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
493 Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
494 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
495 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
496
497 // Add a call to poison all external globals before the given function starts.
498 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
499
500 // Add calls to unpoison all globals before each return instruction.
501 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
502 I != E; ++I) {
503 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
504 CallInst::Create(AsanUnpoisonGlobals, "", RI);
505 }
506 }
507}
508
509bool AddressSanitizer::ShouldInstrumentGlobal(GlobalVariable *G) {
510 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000511 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000512
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000513 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000514 if (!Ty->isSized()) return false;
515 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000516 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000517 // Touch only those globals that will not be defined in other modules.
518 // Don't handle ODR type linkages since other modules may be built w/o asan.
519 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
520 G->getLinkage() != GlobalVariable::PrivateLinkage &&
521 G->getLinkage() != GlobalVariable::InternalLinkage)
522 return false;
523 // Two problems with thread-locals:
524 // - The address of the main thread's copy can't be computed at link-time.
525 // - Need to poison all copies, not just the main thread's one.
526 if (G->isThreadLocal())
527 return false;
528 // For now, just ignore this Alloca if the alignment is large.
529 if (G->getAlignment() > RedzoneSize) return false;
530
531 // Ignore all the globals with the names starting with "\01L_OBJC_".
532 // Many of those are put into the .cstring section. The linker compresses
533 // that section by removing the spare \0s after the string terminator, so
534 // our redzones get broken.
535 if ((G->getName().find("\01L_OBJC_") == 0) ||
536 (G->getName().find("\01l_OBJC_") == 0)) {
537 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
538 return false;
539 }
540
541 if (G->hasSection()) {
542 StringRef Section(G->getSection());
543 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
544 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
545 // them.
546 if ((Section.find("__OBJC,") == 0) ||
547 (Section.find("__DATA, __objc_") == 0)) {
548 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
549 return false;
550 }
551 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
552 // Constant CFString instances are compiled in the following way:
553 // -- the string buffer is emitted into
554 // __TEXT,__cstring,cstring_literals
555 // -- the constant NSConstantString structure referencing that buffer
556 // is placed into __DATA,__cfstring
557 // Therefore there's no point in placing redzones into __DATA,__cfstring.
558 // Moreover, it causes the linker to crash on OS X 10.7
559 if (Section.find("__DATA,__cfstring") == 0) {
560 DEBUG(dbgs() << "Ignoring CFString: " << *G);
561 return false;
562 }
563 }
564
565 return true;
566}
567
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000568// This function replaces all global variables with new variables that have
569// trailing redzones. It also creates a function that poisons
570// redzones and inserts this function into llvm.global_ctors.
571bool AddressSanitizer::insertGlobalRedzones(Module &M) {
572 SmallVector<GlobalVariable *, 16> GlobalsToChange;
573
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000574 for (Module::GlobalListType::iterator G = M.global_begin(),
575 E = M.global_end(); G != E; ++G) {
576 if (ShouldInstrumentGlobal(G))
577 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000578 }
579
580 size_t n = GlobalsToChange.size();
581 if (n == 0) return false;
582
583 // A global is described by a structure
584 // size_t beg;
585 // size_t size;
586 // size_t size_with_redzone;
587 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000588 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000589 // We initialize an array of such structures and pass it to a run-time call.
590 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000591 IntptrTy, IntptrTy,
592 IntptrTy, NULL);
593 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000594
595 IRBuilder<> IRB(CtorInsertBefore);
596
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000597 // The addresses of the first and last dynamically initialized globals in
598 // this TU. Used in initialization order checking.
599 Value *FirstDynamic = 0, *LastDynamic = 0;
600
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000601 for (size_t i = 0; i < n; i++) {
602 GlobalVariable *G = GlobalsToChange[i];
603 PointerType *PtrTy = cast<PointerType>(G->getType());
604 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000605 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000606 uint64_t RightRedzoneSize = RedzoneSize +
607 (RedzoneSize - (SizeInBytes % RedzoneSize));
608 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000609 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000610 bool GlobalHasDynamicInitializer =
611 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000612 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000613 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000614
615 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
616 Constant *NewInitializer = ConstantStruct::get(
617 NewTy, G->getInitializer(),
618 Constant::getNullValue(RightRedZoneTy), NULL);
619
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000620 SmallString<2048> DescriptionOfGlobal = G->getName();
621 DescriptionOfGlobal += " (";
622 DescriptionOfGlobal += M.getModuleIdentifier();
623 DescriptionOfGlobal += ")";
624 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000625
626 // Create a new global variable with enough space for a redzone.
627 GlobalVariable *NewGlobal = new GlobalVariable(
628 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000629 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000630 NewGlobal->copyAttributesFrom(G);
631 NewGlobal->setAlignment(RedzoneSize);
632
633 Value *Indices2[2];
634 Indices2[0] = IRB.getInt32(0);
635 Indices2[1] = IRB.getInt32(0);
636
637 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000638 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000639 NewGlobal->takeName(G);
640 G->eraseFromParent();
641
642 Initializers[i] = ConstantStruct::get(
643 GlobalStructTy,
644 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
645 ConstantInt::get(IntptrTy, SizeInBytes),
646 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
647 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000648 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000649 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000650
651 // Populate the first and last globals declared in this TU.
652 if (ClInitializers && GlobalHasDynamicInitializer) {
653 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
654 if (FirstDynamic == 0)
655 FirstDynamic = LastDynamic;
656 }
657
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000658 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000659 }
660
661 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
662 GlobalVariable *AllGlobals = new GlobalVariable(
663 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
664 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
665
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000666 // Create calls for poisoning before initializers run and unpoisoning after.
667 if (ClInitializers && FirstDynamic && LastDynamic)
668 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
669
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000670 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000671 kAsanRegisterGlobalsName, IRB.getVoidTy(),
672 IntptrTy, IntptrTy, NULL));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000673 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
674
675 IRB.CreateCall2(AsanRegisterGlobals,
676 IRB.CreatePointerCast(AllGlobals, IntptrTy),
677 ConstantInt::get(IntptrTy, n));
678
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000679 // We also need to unregister globals at the end, e.g. when a shared library
680 // gets closed.
681 Function *AsanDtorFunction = Function::Create(
682 FunctionType::get(Type::getVoidTy(*C), false),
683 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
684 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
685 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000686 Function *AsanUnregisterGlobals =
687 checkInterfaceFunction(M.getOrInsertFunction(
688 kAsanUnregisterGlobalsName,
689 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000690 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
691
692 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
693 IRB.CreatePointerCast(AllGlobals, IntptrTy),
694 ConstantInt::get(IntptrTy, n));
695 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
696
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000697 DEBUG(dbgs() << M);
698 return true;
699}
700
701// virtual
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000702bool AddressSanitizer::doInitialization(Module &M) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000703 // Initialize the private fields. No one has accessed them before.
Micah Villmow3574eca2012-10-08 16:38:25 +0000704 TD = getAnalysisIfAvailable<DataLayout>();
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000705
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000706 if (!TD)
707 return false;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000708 BL.reset(new BlackList(ClBlackListFile));
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000709 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000710
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000711 C = &(M.getContext());
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000712 LongSize = TD->getPointerSizeInBits();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000713 IntptrTy = Type::getIntNTy(*C, LongSize);
714 IntptrPtrTy = PointerType::get(IntptrTy, 0);
715
716 AsanCtorFunction = Function::Create(
717 FunctionType::get(Type::getVoidTy(*C), false),
718 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
719 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
720 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
721
722 // call __asan_init in the module ctor.
723 IRBuilder<> IRB(CtorInsertBefore);
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000724 AsanInitFunction = checkInterfaceFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000725 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
726 AsanInitFunction->setLinkage(Function::ExternalLinkage);
727 IRB.CreateCall(AsanInitFunction);
728
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000729 // Create __asan_report* callbacks.
730 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
731 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
732 AccessSizeIndex++) {
733 // IsWrite and TypeSize are encoded in the function name.
734 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
735 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000736 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000737 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
738 checkInterfaceFunction(M.getOrInsertFunction(
739 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000740 }
741 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000742
743 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
744 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
745 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
746 kAsanStackFreeName, IRB.getVoidTy(),
747 IntptrTy, IntptrTy, IntptrTy, NULL));
748 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
749 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
750
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000751 // We insert an empty inline asm after __asan_report* to avoid callback merge.
752 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
753 StringRef(""), StringRef(""),
754 /*hasSideEffects=*/true);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000755
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000756 llvm::Triple targetTriple(M.getTargetTriple());
Logan Chien43bf7092012-09-02 09:29:46 +0000757 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000758
759 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
760 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000761 if (ClMappingOffsetLog >= 0) {
762 if (ClMappingOffsetLog == 0) {
763 // special case
764 MappingOffset = 0;
765 } else {
766 MappingOffset = 1ULL << ClMappingOffsetLog;
767 }
768 }
769 MappingScale = kDefaultShadowScale;
770 if (ClMappingScale) {
771 MappingScale = ClMappingScale;
772 }
773 // Redzone used for stack and globals is at least 32 bytes.
774 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
775 RedzoneSize = std::max(32, (int)(1 << MappingScale));
776
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000777
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000778 if (ClMappingOffsetLog >= 0) {
779 // Tell the run-time the current values of mapping offset and scale.
780 GlobalValue *asan_mapping_offset =
781 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
782 ConstantInt::get(IntptrTy, MappingOffset),
783 kAsanMappingOffsetName);
784 // Read the global, otherwise it may be optimized away.
785 IRB.CreateLoad(asan_mapping_offset, true);
786 }
787 if (ClMappingScale) {
788 GlobalValue *asan_mapping_scale =
789 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
790 ConstantInt::get(IntptrTy, MappingScale),
791 kAsanMappingScaleName);
792 // Read the global, otherwise it may be optimized away.
793 IRB.CreateLoad(asan_mapping_scale, true);
794 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000795
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000796 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000797
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000798 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000799}
800
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000801bool AddressSanitizer::doFinalization(Module &M) {
802 // We transform the globals at the very end so that the optimization analysis
803 // works on the original globals.
804 if (ClGlobals)
805 return insertGlobalRedzones(M);
806 return false;
807}
808
809
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000810bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
811 // For each NSObject descendant having a +load method, this method is invoked
812 // by the ObjC runtime before any of the static constructors is called.
813 // Therefore we need to instrument such methods with a call to __asan_init
814 // at the beginning in order to initialize our runtime before any access to
815 // the shadow memory.
816 // We cannot just ignore these methods, because they may call other
817 // instrumented functions.
818 if (F.getName().find(" load]") != std::string::npos) {
819 IRBuilder<> IRB(F.begin()->begin());
820 IRB.CreateCall(AsanInitFunction);
821 return true;
822 }
823 return false;
824}
825
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000826bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000827 if (BL->isIn(F)) return false;
828 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000829 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000830
831 // If needed, insert __asan_init before checking for AddressSafety attr.
832 maybeInsertAsanInitAtFunctionEntry(F);
833
Bill Wendling67658342012-10-09 07:45:08 +0000834 if (!F.getFnAttributes().hasAttribute(Attributes::AddressSafety))
835 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000836
837 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
838 return false;
Bill Wendling67658342012-10-09 07:45:08 +0000839
840 // We want to instrument every address only once per basic block (unless there
841 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000842 SmallSet<Value*, 16> TempsToInstrument;
843 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000844 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000845 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000846
847 // Fill the set of memory operations to instrument.
848 for (Function::iterator FI = F.begin(), FE = F.end();
849 FI != FE; ++FI) {
850 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000851 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000852 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
853 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000854 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000855 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000856 if (ClOpt && ClOptSameTemp) {
857 if (!TempsToInstrument.insert(Addr))
858 continue; // We've seen this temp in the current BB.
859 }
860 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
861 // ok, take it.
862 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000863 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000864 // A call inside BB.
865 TempsToInstrument.clear();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000866 if (CI->doesNotReturn()) {
867 NoReturnCalls.push_back(CI);
868 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000869 }
870 continue;
871 }
872 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000873 NumInsnsPerBB++;
874 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
875 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000876 }
877 }
878
879 // Instrument.
880 int NumInstrumented = 0;
881 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
882 Instruction *Inst = ToInstrument[i];
883 if (ClDebugMin < 0 || ClDebugMax < 0 ||
884 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000885 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000886 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000887 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000888 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000889 }
890 NumInstrumented++;
891 }
892
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000893 bool ChangedStack = poisonStackInFunction(F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000894
895 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
896 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
897 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
898 Instruction *CI = NoReturnCalls[i];
899 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000900 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000901 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000902 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000903
904 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000905}
906
907static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
908 if (ShadowRedzoneSize == 1) return PoisonByte;
909 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
910 if (ShadowRedzoneSize == 4)
911 return (PoisonByte << 24) + (PoisonByte << 16) +
912 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000913 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000914}
915
916static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
917 size_t Size,
918 size_t RedzoneSize,
919 size_t ShadowGranularity,
920 uint8_t Magic) {
921 for (size_t i = 0; i < RedzoneSize;
922 i+= ShadowGranularity, Shadow++) {
923 if (i + ShadowGranularity <= Size) {
924 *Shadow = 0; // fully addressable
925 } else if (i >= Size) {
926 *Shadow = Magic; // unaddressable
927 } else {
928 *Shadow = Size - i; // first Size-i bytes are addressable
929 }
930 }
931}
932
933void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
934 IRBuilder<> IRB,
935 Value *ShadowBase, bool DoPoison) {
936 size_t ShadowRZSize = RedzoneSize >> MappingScale;
937 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
938 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
939 Type *RZPtrTy = PointerType::get(RZTy, 0);
940
941 Value *PoisonLeft = ConstantInt::get(RZTy,
942 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
943 Value *PoisonMid = ConstantInt::get(RZTy,
944 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
945 Value *PoisonRight = ConstantInt::get(RZTy,
946 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
947
948 // poison the first red zone.
949 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
950
951 // poison all other red zones.
952 uint64_t Pos = RedzoneSize;
953 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
954 AllocaInst *AI = AllocaVec[i];
955 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
956 uint64_t AlignedSize = getAlignedAllocaSize(AI);
957 assert(AlignedSize - SizeInBytes < RedzoneSize);
958 Value *Ptr = NULL;
959
960 Pos += AlignedSize;
961
962 assert(ShadowBase->getType() == IntptrTy);
963 if (SizeInBytes < AlignedSize) {
964 // Poison the partial redzone at right
965 Ptr = IRB.CreateAdd(
966 ShadowBase, ConstantInt::get(IntptrTy,
967 (Pos >> MappingScale) - ShadowRZSize));
968 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
969 uint32_t Poison = 0;
970 if (DoPoison) {
971 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
972 RedzoneSize,
973 1ULL << MappingScale,
974 kAsanStackPartialRedzoneMagic);
975 }
976 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
977 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
978 }
979
980 // Poison the full redzone at right.
981 Ptr = IRB.CreateAdd(ShadowBase,
982 ConstantInt::get(IntptrTy, Pos >> MappingScale));
983 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
984 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
985
986 Pos += RedzoneSize;
987 }
988}
989
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000990// Workaround for bug 11395: we don't want to instrument stack in functions
991// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000992// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000993bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
994 if (LongSize != 32) return false;
995 CallInst *CI = dyn_cast<CallInst>(I);
996 if (!CI || !CI->isInlineAsm()) return false;
997 if (CI->getNumArgOperands() <= 5) return false;
998 // We have inline assembly with quite a few arguments.
999 return true;
1000}
1001
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001002// Find all static Alloca instructions and put
1003// poisoned red zones around all of them.
1004// Then unpoison everything back before the function returns.
1005//
1006// Stack poisoning does not play well with exception handling.
1007// When an exception is thrown, we essentially bypass the code
1008// that unpoisones the stack. This is why the run-time library has
1009// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
1010// stack in the interceptor. This however does not work inside the
1011// actual function which catches the exception. Most likely because the
1012// compiler hoists the load of the shadow value somewhere too high.
1013// This causes asan to report a non-existing bug on 453.povray.
1014// It sounds like an LLVM bug.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001015bool AddressSanitizer::poisonStackInFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001016 if (!ClStack) return false;
1017 SmallVector<AllocaInst*, 16> AllocaVec;
1018 SmallVector<Instruction*, 8> RetVec;
1019 uint64_t TotalSize = 0;
1020
1021 // Filter out Alloca instructions we want (and can) handle.
1022 // Collect Ret instructions.
1023 for (Function::iterator FI = F.begin(), FE = F.end();
1024 FI != FE; ++FI) {
1025 BasicBlock &BB = *FI;
1026 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1027 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001028 if (isa<ReturnInst>(BI)) {
1029 RetVec.push_back(BI);
1030 continue;
1031 }
1032
1033 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1034 if (!AI) continue;
1035 if (AI->isArrayAllocation()) continue;
1036 if (!AI->isStaticAlloca()) continue;
1037 if (!AI->getAllocatedType()->isSized()) continue;
1038 if (AI->getAlignment() > RedzoneSize) continue;
1039 AllocaVec.push_back(AI);
1040 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1041 TotalSize += AlignedSize;
1042 }
1043 }
1044
1045 if (AllocaVec.empty()) return false;
1046
1047 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
1048
1049 bool DoStackMalloc = ClUseAfterReturn
1050 && LocalStackSize <= kMaxStackMallocSize;
1051
1052 Instruction *InsBefore = AllocaVec[0];
1053 IRBuilder<> IRB(InsBefore);
1054
1055
1056 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1057 AllocaInst *MyAlloca =
1058 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1059 MyAlloca->setAlignment(RedzoneSize);
1060 assert(MyAlloca->isStaticAlloca());
1061 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1062 Value *LocalStackBase = OrigStackBase;
1063
1064 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001065 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1066 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1067 }
1068
1069 // This string will be parsed by the run-time (DescribeStackAddress).
1070 SmallString<2048> StackDescriptionStorage;
1071 raw_svector_ostream StackDescription(StackDescriptionStorage);
1072 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1073
1074 uint64_t Pos = RedzoneSize;
1075 // Replace Alloca instructions with base+offset.
1076 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1077 AllocaInst *AI = AllocaVec[i];
1078 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1079 StringRef Name = AI->getName();
1080 StackDescription << Pos << " " << SizeInBytes << " "
1081 << Name.size() << " " << Name << " ";
1082 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1083 assert((AlignedSize % RedzoneSize) == 0);
1084 AI->replaceAllUsesWith(
1085 IRB.CreateIntToPtr(
1086 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1087 AI->getType()));
1088 Pos += AlignedSize + RedzoneSize;
1089 }
1090 assert(Pos == LocalStackSize);
1091
1092 // Write the Magic value and the frame description constant to the redzone.
1093 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1094 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1095 BasePlus0);
1096 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1097 ConstantInt::get(IntptrTy, LongSize/8));
1098 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001099 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001100 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001101 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001102 IRB.CreateStore(Description, BasePlus1);
1103
1104 // Poison the stack redzones at the entry.
1105 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1106 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1107
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001108 // Unpoison the stack before all ret instructions.
1109 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1110 Instruction *Ret = RetVec[i];
1111 IRBuilder<> IRBRet(Ret);
1112
1113 // Mark the current frame as retired.
1114 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1115 BasePlus0);
1116 // Unpoison the stack.
1117 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1118
1119 if (DoStackMalloc) {
1120 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1121 ConstantInt::get(IntptrTy, LocalStackSize),
1122 OrigStackBase);
1123 }
1124 }
1125
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001126 // We are done. Remove the old unused alloca instructions.
1127 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1128 AllocaVec[i]->eraseFromParent();
1129
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001130 if (ClDebugStack) {
1131 DEBUG(dbgs() << F);
1132 }
1133
1134 return true;
1135}