1 //===-- echo.cpp - tool for testing libLLVM and llvm-c API ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the --echo command in llvm-c-test.
12 // This command uses the C API to read a module and output an exact copy of it
13 // as output. It is used to check that the resulting module matches the input
14 // to validate that the C API can read and write modules properly.
16 //===----------------------------------------------------------------------===//
18 #include "llvm-c-test.h"
19 #include "llvm-c/DebugInfo.h"
20 #include "llvm-c/Target.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/Support/ErrorHandling.h"
29 // Provide DenseMapInfo for C API opaque types.
31 struct CAPIDenseMap
{};
33 // The default DenseMapInfo require to know about pointer alignement.
34 // Because the C API uses opaques pointer types, their alignement is unknown.
35 // As a result, we need to roll out our own implementation.
37 struct CAPIDenseMap
<T
*> {
38 struct CAPIDenseMapInfo
{
39 static inline T
* getEmptyKey() {
40 uintptr_t Val
= static_cast<uintptr_t>(-1);
41 return reinterpret_cast<T
*>(Val
);
43 static inline T
* getTombstoneKey() {
44 uintptr_t Val
= static_cast<uintptr_t>(-2);
45 return reinterpret_cast<T
*>(Val
);
47 static unsigned getHashValue(const T
*PtrVal
) {
48 return hash_value(PtrVal
);
50 static bool isEqual(const T
*LHS
, const T
*RHS
) { return LHS
== RHS
; }
53 typedef DenseMap
<T
*, T
*, CAPIDenseMapInfo
> Map
;
56 typedef CAPIDenseMap
<LLVMValueRef
>::Map ValueMap
;
57 typedef CAPIDenseMap
<LLVMBasicBlockRef
>::Map BasicBlockMap
;
63 TypeCloner(LLVMModuleRef M
): M(M
), Ctx(LLVMGetModuleContext(M
)) {}
65 LLVMTypeRef
Clone(LLVMValueRef Src
) {
66 return Clone(LLVMTypeOf(Src
));
69 LLVMTypeRef
Clone(LLVMTypeRef Src
) {
70 LLVMTypeKind Kind
= LLVMGetTypeKind(Src
);
72 case LLVMVoidTypeKind
:
73 return LLVMVoidTypeInContext(Ctx
);
74 case LLVMHalfTypeKind
:
75 return LLVMHalfTypeInContext(Ctx
);
76 case LLVMFloatTypeKind
:
77 return LLVMFloatTypeInContext(Ctx
);
78 case LLVMDoubleTypeKind
:
79 return LLVMDoubleTypeInContext(Ctx
);
80 case LLVMX86_FP80TypeKind
:
81 return LLVMX86FP80TypeInContext(Ctx
);
82 case LLVMFP128TypeKind
:
83 return LLVMFP128TypeInContext(Ctx
);
84 case LLVMPPC_FP128TypeKind
:
85 return LLVMPPCFP128TypeInContext(Ctx
);
86 case LLVMLabelTypeKind
:
87 return LLVMLabelTypeInContext(Ctx
);
88 case LLVMIntegerTypeKind
:
89 return LLVMIntTypeInContext(Ctx
, LLVMGetIntTypeWidth(Src
));
90 case LLVMFunctionTypeKind
: {
91 unsigned ParamCount
= LLVMCountParamTypes(Src
);
92 LLVMTypeRef
* Params
= nullptr;
94 Params
= static_cast<LLVMTypeRef
*>(
95 safe_malloc(ParamCount
* sizeof(LLVMTypeRef
)));
96 LLVMGetParamTypes(Src
, Params
);
97 for (unsigned i
= 0; i
< ParamCount
; i
++)
98 Params
[i
] = Clone(Params
[i
]);
101 LLVMTypeRef FunTy
= LLVMFunctionType(Clone(LLVMGetReturnType(Src
)),
103 LLVMIsFunctionVarArg(Src
));
108 case LLVMStructTypeKind
: {
109 LLVMTypeRef S
= nullptr;
110 const char *Name
= LLVMGetStructName(Src
);
112 S
= LLVMGetTypeByName(M
, Name
);
115 S
= LLVMStructCreateNamed(Ctx
, Name
);
116 if (LLVMIsOpaqueStruct(Src
))
120 unsigned EltCount
= LLVMCountStructElementTypes(Src
);
121 SmallVector
<LLVMTypeRef
, 8> Elts
;
122 for (unsigned i
= 0; i
< EltCount
; i
++)
123 Elts
.push_back(Clone(LLVMStructGetTypeAtIndex(Src
, i
)));
125 LLVMStructSetBody(S
, Elts
.data(), EltCount
, LLVMIsPackedStruct(Src
));
127 S
= LLVMStructTypeInContext(Ctx
, Elts
.data(), EltCount
,
128 LLVMIsPackedStruct(Src
));
131 case LLVMArrayTypeKind
:
132 return LLVMArrayType(
133 Clone(LLVMGetElementType(Src
)),
134 LLVMGetArrayLength(Src
)
136 case LLVMPointerTypeKind
:
137 return LLVMPointerType(
138 Clone(LLVMGetElementType(Src
)),
139 LLVMGetPointerAddressSpace(Src
)
141 case LLVMVectorTypeKind
:
142 return LLVMVectorType(
143 Clone(LLVMGetElementType(Src
)),
144 LLVMGetVectorSize(Src
)
146 case LLVMMetadataTypeKind
:
147 return LLVMMetadataTypeInContext(Ctx
);
148 case LLVMX86_MMXTypeKind
:
149 return LLVMX86MMXTypeInContext(Ctx
);
150 case LLVMTokenTypeKind
:
151 return LLVMTokenTypeInContext(Ctx
);
154 fprintf(stderr
, "%d is not a supported typekind\n", Kind
);
159 static ValueMap
clone_params(LLVMValueRef Src
, LLVMValueRef Dst
) {
160 unsigned Count
= LLVMCountParams(Src
);
161 if (Count
!= LLVMCountParams(Dst
))
162 report_fatal_error("Parameter count mismatch");
168 LLVMValueRef SrcFirst
= LLVMGetFirstParam(Src
);
169 LLVMValueRef DstFirst
= LLVMGetFirstParam(Dst
);
170 LLVMValueRef SrcLast
= LLVMGetLastParam(Src
);
171 LLVMValueRef DstLast
= LLVMGetLastParam(Dst
);
173 LLVMValueRef SrcCur
= SrcFirst
;
174 LLVMValueRef DstCur
= DstFirst
;
175 LLVMValueRef SrcNext
= nullptr;
176 LLVMValueRef DstNext
= nullptr;
179 const char *Name
= LLVMGetValueName2(SrcCur
, &NameLen
);
180 LLVMSetValueName2(DstCur
, Name
, NameLen
);
182 VMap
[SrcCur
] = DstCur
;
185 SrcNext
= LLVMGetNextParam(SrcCur
);
186 DstNext
= LLVMGetNextParam(DstCur
);
187 if (SrcNext
== nullptr && DstNext
== nullptr) {
188 if (SrcCur
!= SrcLast
)
189 report_fatal_error("SrcLast param does not match End");
190 if (DstCur
!= DstLast
)
191 report_fatal_error("DstLast param does not match End");
195 if (SrcNext
== nullptr)
196 report_fatal_error("SrcNext was unexpectedly null");
197 if (DstNext
== nullptr)
198 report_fatal_error("DstNext was unexpectedly null");
200 LLVMValueRef SrcPrev
= LLVMGetPreviousParam(SrcNext
);
201 if (SrcPrev
!= SrcCur
)
202 report_fatal_error("SrcNext.Previous param is not Current");
204 LLVMValueRef DstPrev
= LLVMGetPreviousParam(DstNext
);
205 if (DstPrev
!= DstCur
)
206 report_fatal_error("DstNext.Previous param is not Current");
213 report_fatal_error("Parameter count does not match iteration");
218 static void check_value_kind(LLVMValueRef V
, LLVMValueKind K
) {
219 if (LLVMGetValueKind(V
) != K
)
220 report_fatal_error("LLVMGetValueKind returned incorrect type");
223 static LLVMValueRef
clone_constant_impl(LLVMValueRef Cst
, LLVMModuleRef M
);
225 static LLVMValueRef
clone_constant(LLVMValueRef Cst
, LLVMModuleRef M
) {
226 LLVMValueRef Ret
= clone_constant_impl(Cst
, M
);
227 check_value_kind(Ret
, LLVMGetValueKind(Cst
));
231 static LLVMValueRef
clone_constant_impl(LLVMValueRef Cst
, LLVMModuleRef M
) {
232 if (!LLVMIsAConstant(Cst
))
233 report_fatal_error("Expected a constant");
235 // Maybe it is a symbol
236 if (LLVMIsAGlobalValue(Cst
)) {
238 const char *Name
= LLVMGetValueName2(Cst
, &NameLen
);
241 if (LLVMIsAFunction(Cst
)) {
242 check_value_kind(Cst
, LLVMFunctionValueKind
);
243 LLVMValueRef Dst
= LLVMGetNamedFunction(M
, Name
);
246 report_fatal_error("Could not find function");
249 // Try global variable
250 if (LLVMIsAGlobalVariable(Cst
)) {
251 check_value_kind(Cst
, LLVMGlobalVariableValueKind
);
252 LLVMValueRef Dst
= LLVMGetNamedGlobal(M
, Name
);
255 report_fatal_error("Could not find variable");
259 if (LLVMIsAGlobalAlias(Cst
)) {
260 check_value_kind(Cst
, LLVMGlobalAliasValueKind
);
261 LLVMValueRef Dst
= LLVMGetNamedGlobalAlias(M
, Name
, NameLen
);
264 report_fatal_error("Could not find alias");
267 fprintf(stderr
, "Could not find @%s\n", Name
);
271 // Try integer literal
272 if (LLVMIsAConstantInt(Cst
)) {
273 check_value_kind(Cst
, LLVMConstantIntValueKind
);
274 return LLVMConstInt(TypeCloner(M
).Clone(Cst
),
275 LLVMConstIntGetZExtValue(Cst
), false);
278 // Try zeroinitializer
279 if (LLVMIsAConstantAggregateZero(Cst
)) {
280 check_value_kind(Cst
, LLVMConstantAggregateZeroValueKind
);
281 return LLVMConstNull(TypeCloner(M
).Clone(Cst
));
284 // Try constant array
285 if (LLVMIsAConstantArray(Cst
)) {
286 check_value_kind(Cst
, LLVMConstantArrayValueKind
);
287 LLVMTypeRef Ty
= TypeCloner(M
).Clone(Cst
);
288 unsigned EltCount
= LLVMGetArrayLength(Ty
);
289 SmallVector
<LLVMValueRef
, 8> Elts
;
290 for (unsigned i
= 0; i
< EltCount
; i
++)
291 Elts
.push_back(clone_constant(LLVMGetOperand(Cst
, i
), M
));
292 return LLVMConstArray(LLVMGetElementType(Ty
), Elts
.data(), EltCount
);
295 // Try contant data array
296 if (LLVMIsAConstantDataArray(Cst
)) {
297 check_value_kind(Cst
, LLVMConstantDataArrayValueKind
);
298 LLVMTypeRef Ty
= TypeCloner(M
).Clone(Cst
);
299 unsigned EltCount
= LLVMGetArrayLength(Ty
);
300 SmallVector
<LLVMValueRef
, 8> Elts
;
301 for (unsigned i
= 0; i
< EltCount
; i
++)
302 Elts
.push_back(clone_constant(LLVMGetElementAsConstant(Cst
, i
), M
));
303 return LLVMConstArray(LLVMGetElementType(Ty
), Elts
.data(), EltCount
);
306 // Try constant struct
307 if (LLVMIsAConstantStruct(Cst
)) {
308 check_value_kind(Cst
, LLVMConstantStructValueKind
);
309 LLVMTypeRef Ty
= TypeCloner(M
).Clone(Cst
);
310 unsigned EltCount
= LLVMCountStructElementTypes(Ty
);
311 SmallVector
<LLVMValueRef
, 8> Elts
;
312 for (unsigned i
= 0; i
< EltCount
; i
++)
313 Elts
.push_back(clone_constant(LLVMGetOperand(Cst
, i
), M
));
314 if (LLVMGetStructName(Ty
))
315 return LLVMConstNamedStruct(Ty
, Elts
.data(), EltCount
);
316 return LLVMConstStructInContext(LLVMGetModuleContext(M
), Elts
.data(),
317 EltCount
, LLVMIsPackedStruct(Ty
));
321 if (LLVMIsUndef(Cst
)) {
322 check_value_kind(Cst
, LLVMUndefValueValueKind
);
323 return LLVMGetUndef(TypeCloner(M
).Clone(Cst
));
327 if (LLVMIsNull(Cst
)) {
328 check_value_kind(Cst
, LLVMConstantTokenNoneValueKind
);
329 LLVMTypeRef Ty
= TypeCloner(M
).Clone(Cst
);
330 return LLVMConstNull(Ty
);
334 if (LLVMIsAConstantFP(Cst
)) {
335 check_value_kind(Cst
, LLVMConstantFPValueKind
);
336 report_fatal_error("ConstantFP is not supported");
339 // This kind of constant is not supported
340 if (!LLVMIsAConstantExpr(Cst
))
341 report_fatal_error("Expected a constant expression");
343 // At this point, it must be a constant expression
344 check_value_kind(Cst
, LLVMConstantExprValueKind
);
346 LLVMOpcode Op
= LLVMGetConstOpcode(Cst
);
349 return LLVMConstBitCast(clone_constant(LLVMGetOperand(Cst
, 0), M
),
350 TypeCloner(M
).Clone(Cst
));
352 fprintf(stderr
, "%d is not a supported opcode\n", Op
);
364 FunCloner(LLVMValueRef Src
, LLVMValueRef Dst
): Fun(Dst
),
365 M(LLVMGetGlobalParent(Fun
)), VMap(clone_params(Src
, Dst
)) {}
367 LLVMTypeRef
CloneType(LLVMTypeRef Src
) {
368 return TypeCloner(M
).Clone(Src
);
371 LLVMTypeRef
CloneType(LLVMValueRef Src
) {
372 return TypeCloner(M
).Clone(Src
);
375 // Try to clone everything in the llvm::Value hierarchy.
376 LLVMValueRef
CloneValue(LLVMValueRef Src
) {
377 // First, the value may be constant.
378 if (LLVMIsAConstant(Src
))
379 return clone_constant(Src
, M
);
381 // Function argument should always be in the map already.
382 auto i
= VMap
.find(Src
);
386 if (!LLVMIsAInstruction(Src
))
387 report_fatal_error("Expected an instruction");
389 auto Ctx
= LLVMGetModuleContext(M
);
390 auto Builder
= LLVMCreateBuilderInContext(Ctx
);
391 auto BB
= DeclareBB(LLVMGetInstructionParent(Src
));
392 LLVMPositionBuilderAtEnd(Builder
, BB
);
393 auto Dst
= CloneInstruction(Src
, Builder
);
394 LLVMDisposeBuilder(Builder
);
398 void CloneAttrs(LLVMValueRef Src
, LLVMValueRef Dst
) {
399 auto Ctx
= LLVMGetModuleContext(M
);
400 int ArgCount
= LLVMGetNumArgOperands(Src
);
401 for (int i
= LLVMAttributeReturnIndex
; i
<= ArgCount
; i
++) {
402 for (unsigned k
= 0, e
= LLVMGetLastEnumAttributeKind(); k
< e
; ++k
) {
403 if (auto SrcA
= LLVMGetCallSiteEnumAttribute(Src
, i
, k
)) {
404 auto Val
= LLVMGetEnumAttributeValue(SrcA
);
405 auto A
= LLVMCreateEnumAttribute(Ctx
, k
, Val
);
406 LLVMAddCallSiteAttribute(Dst
, i
, A
);
412 LLVMValueRef
CloneInstruction(LLVMValueRef Src
, LLVMBuilderRef Builder
) {
413 check_value_kind(Src
, LLVMInstructionValueKind
);
414 if (!LLVMIsAInstruction(Src
))
415 report_fatal_error("Expected an instruction");
418 const char *Name
= LLVMGetValueName2(Src
, &NameLen
);
420 // Check if this is something we already computed.
422 auto i
= VMap
.find(Src
);
423 if (i
!= VMap
.end()) {
424 // If we have a hit, it means we already generated the instruction
425 // as a dependancy to somethign else. We need to make sure
426 // it is ordered properly.
428 LLVMInstructionRemoveFromParent(I
);
429 LLVMInsertIntoBuilderWithName(Builder
, I
, Name
);
434 // We tried everything, it must be an instruction
435 // that hasn't been generated already.
436 LLVMValueRef Dst
= nullptr;
438 LLVMOpcode Op
= LLVMGetInstructionOpcode(Src
);
441 int OpCount
= LLVMGetNumOperands(Src
);
443 Dst
= LLVMBuildRetVoid(Builder
);
445 Dst
= LLVMBuildRet(Builder
, CloneValue(LLVMGetOperand(Src
, 0)));
449 if (!LLVMIsConditional(Src
)) {
450 LLVMValueRef SrcOp
= LLVMGetOperand(Src
, 0);
451 LLVMBasicBlockRef SrcBB
= LLVMValueAsBasicBlock(SrcOp
);
452 Dst
= LLVMBuildBr(Builder
, DeclareBB(SrcBB
));
456 LLVMValueRef Cond
= LLVMGetCondition(Src
);
457 LLVMValueRef Else
= LLVMGetOperand(Src
, 1);
458 LLVMBasicBlockRef ElseBB
= DeclareBB(LLVMValueAsBasicBlock(Else
));
459 LLVMValueRef Then
= LLVMGetOperand(Src
, 2);
460 LLVMBasicBlockRef ThenBB
= DeclareBB(LLVMValueAsBasicBlock(Then
));
461 Dst
= LLVMBuildCondBr(Builder
, CloneValue(Cond
), ThenBB
, ElseBB
);
468 SmallVector
<LLVMValueRef
, 8> Args
;
469 int ArgCount
= LLVMGetNumArgOperands(Src
);
470 for (int i
= 0; i
< ArgCount
; i
++)
471 Args
.push_back(CloneValue(LLVMGetOperand(Src
, i
)));
472 LLVMValueRef Fn
= CloneValue(LLVMGetCalledValue(Src
));
473 LLVMBasicBlockRef Then
= DeclareBB(LLVMGetNormalDest(Src
));
474 LLVMBasicBlockRef Unwind
= DeclareBB(LLVMGetUnwindDest(Src
));
475 Dst
= LLVMBuildInvoke(Builder
, Fn
, Args
.data(), ArgCount
,
477 CloneAttrs(Src
, Dst
);
480 case LLVMUnreachable
:
481 Dst
= LLVMBuildUnreachable(Builder
);
484 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
485 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
486 Dst
= LLVMBuildAdd(Builder
, LHS
, RHS
, Name
);
490 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
491 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
492 Dst
= LLVMBuildSub(Builder
, LHS
, RHS
, Name
);
496 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
497 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
498 Dst
= LLVMBuildMul(Builder
, LHS
, RHS
, Name
);
502 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
503 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
504 Dst
= LLVMBuildUDiv(Builder
, LHS
, RHS
, Name
);
508 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
509 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
510 Dst
= LLVMBuildSDiv(Builder
, LHS
, RHS
, Name
);
514 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
515 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
516 Dst
= LLVMBuildURem(Builder
, LHS
, RHS
, Name
);
520 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
521 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
522 Dst
= LLVMBuildSRem(Builder
, LHS
, RHS
, Name
);
526 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
527 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
528 Dst
= LLVMBuildShl(Builder
, LHS
, RHS
, Name
);
532 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
533 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
534 Dst
= LLVMBuildLShr(Builder
, LHS
, RHS
, Name
);
538 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
539 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
540 Dst
= LLVMBuildAShr(Builder
, LHS
, RHS
, Name
);
544 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
545 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
546 Dst
= LLVMBuildAnd(Builder
, LHS
, RHS
, Name
);
550 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
551 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
552 Dst
= LLVMBuildOr(Builder
, LHS
, RHS
, Name
);
556 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
557 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
558 Dst
= LLVMBuildXor(Builder
, LHS
, RHS
, Name
);
562 LLVMTypeRef Ty
= CloneType(LLVMGetAllocatedType(Src
));
563 Dst
= LLVMBuildAlloca(Builder
, Ty
, Name
);
567 LLVMValueRef Ptr
= CloneValue(LLVMGetOperand(Src
, 0));
568 Dst
= LLVMBuildLoad(Builder
, Ptr
, Name
);
569 LLVMSetAlignment(Dst
, LLVMGetAlignment(Src
));
573 LLVMValueRef Val
= CloneValue(LLVMGetOperand(Src
, 0));
574 LLVMValueRef Ptr
= CloneValue(LLVMGetOperand(Src
, 1));
575 Dst
= LLVMBuildStore(Builder
, Val
, Ptr
);
576 LLVMSetAlignment(Dst
, LLVMGetAlignment(Src
));
579 case LLVMGetElementPtr
: {
580 LLVMValueRef Ptr
= CloneValue(LLVMGetOperand(Src
, 0));
581 SmallVector
<LLVMValueRef
, 8> Idx
;
582 int NumIdx
= LLVMGetNumIndices(Src
);
583 for (int i
= 1; i
<= NumIdx
; i
++)
584 Idx
.push_back(CloneValue(LLVMGetOperand(Src
, i
)));
585 if (LLVMIsInBounds(Src
))
586 Dst
= LLVMBuildInBoundsGEP(Builder
, Ptr
, Idx
.data(), NumIdx
, Name
);
588 Dst
= LLVMBuildGEP(Builder
, Ptr
, Idx
.data(), NumIdx
, Name
);
591 case LLVMAtomicCmpXchg
: {
592 LLVMValueRef Ptr
= CloneValue(LLVMGetOperand(Src
, 0));
593 LLVMValueRef Cmp
= CloneValue(LLVMGetOperand(Src
, 1));
594 LLVMValueRef New
= CloneValue(LLVMGetOperand(Src
, 2));
595 LLVMAtomicOrdering Succ
= LLVMGetCmpXchgSuccessOrdering(Src
);
596 LLVMAtomicOrdering Fail
= LLVMGetCmpXchgFailureOrdering(Src
);
597 LLVMBool SingleThread
= LLVMIsAtomicSingleThread(Src
);
599 Dst
= LLVMBuildAtomicCmpXchg(Builder
, Ptr
, Cmp
, New
, Succ
, Fail
,
603 LLVMValueRef V
= CloneValue(LLVMGetOperand(Src
, 0));
604 Dst
= LLVMBuildBitCast(Builder
, V
, CloneType(Src
), Name
);
608 LLVMIntPredicate Pred
= LLVMGetICmpPredicate(Src
);
609 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
610 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
611 Dst
= LLVMBuildICmp(Builder
, Pred
, LHS
, RHS
, Name
);
615 // We need to aggressively set things here because of loops.
616 VMap
[Src
] = Dst
= LLVMBuildPhi(Builder
, CloneType(Src
), Name
);
618 SmallVector
<LLVMValueRef
, 8> Values
;
619 SmallVector
<LLVMBasicBlockRef
, 8> Blocks
;
621 unsigned IncomingCount
= LLVMCountIncoming(Src
);
622 for (unsigned i
= 0; i
< IncomingCount
; ++i
) {
623 Blocks
.push_back(DeclareBB(LLVMGetIncomingBlock(Src
, i
)));
624 Values
.push_back(CloneValue(LLVMGetIncomingValue(Src
, i
)));
627 LLVMAddIncoming(Dst
, Values
.data(), Blocks
.data(), IncomingCount
);
631 SmallVector
<LLVMValueRef
, 8> Args
;
632 int ArgCount
= LLVMGetNumArgOperands(Src
);
633 for (int i
= 0; i
< ArgCount
; i
++)
634 Args
.push_back(CloneValue(LLVMGetOperand(Src
, i
)));
635 LLVMValueRef Fn
= CloneValue(LLVMGetCalledValue(Src
));
636 Dst
= LLVMBuildCall(Builder
, Fn
, Args
.data(), ArgCount
, Name
);
637 LLVMSetTailCall(Dst
, LLVMIsTailCall(Src
));
638 CloneAttrs(Src
, Dst
);
642 Dst
= LLVMBuildResume(Builder
, CloneValue(LLVMGetOperand(Src
, 0)));
645 case LLVMLandingPad
: {
646 // The landing pad API is a bit screwed up for historical reasons.
647 Dst
= LLVMBuildLandingPad(Builder
, CloneType(Src
), nullptr, 0, Name
);
648 unsigned NumClauses
= LLVMGetNumClauses(Src
);
649 for (unsigned i
= 0; i
< NumClauses
; ++i
)
650 LLVMAddClause(Dst
, CloneValue(LLVMGetClause(Src
, i
)));
651 LLVMSetCleanup(Dst
, LLVMIsCleanup(Src
));
654 case LLVMCleanupRet
: {
655 LLVMValueRef CatchPad
= CloneValue(LLVMGetOperand(Src
, 0));
656 LLVMBasicBlockRef Unwind
= nullptr;
657 if (LLVMBasicBlockRef UDest
= LLVMGetUnwindDest(Src
))
658 Unwind
= DeclareBB(UDest
);
659 Dst
= LLVMBuildCleanupRet(Builder
, CatchPad
, Unwind
);
663 LLVMValueRef CatchPad
= CloneValue(LLVMGetOperand(Src
, 0));
664 LLVMBasicBlockRef SuccBB
= DeclareBB(LLVMGetSuccessor(Src
, 0));
665 Dst
= LLVMBuildCatchRet(Builder
, CatchPad
, SuccBB
);
669 LLVMValueRef ParentPad
= CloneValue(LLVMGetParentCatchSwitch(Src
));
670 SmallVector
<LLVMValueRef
, 8> Args
;
671 int ArgCount
= LLVMGetNumArgOperands(Src
);
672 for (int i
= 0; i
< ArgCount
; i
++)
673 Args
.push_back(CloneValue(LLVMGetOperand(Src
, i
)));
674 Dst
= LLVMBuildCatchPad(Builder
, ParentPad
,
675 Args
.data(), ArgCount
, Name
);
678 case LLVMCleanupPad
: {
679 LLVMValueRef ParentPad
= CloneValue(LLVMGetOperand(Src
, 0));
680 SmallVector
<LLVMValueRef
, 8> Args
;
681 int ArgCount
= LLVMGetNumArgOperands(Src
);
682 for (int i
= 0; i
< ArgCount
; i
++)
683 Args
.push_back(CloneValue(LLVMGetArgOperand(Src
, i
)));
684 Dst
= LLVMBuildCleanupPad(Builder
, ParentPad
,
685 Args
.data(), ArgCount
, Name
);
688 case LLVMCatchSwitch
: {
689 LLVMValueRef ParentPad
= CloneValue(LLVMGetOperand(Src
, 0));
690 LLVMBasicBlockRef UnwindBB
= nullptr;
691 if (LLVMBasicBlockRef UDest
= LLVMGetUnwindDest(Src
)) {
692 UnwindBB
= DeclareBB(UDest
);
694 unsigned NumHandlers
= LLVMGetNumHandlers(Src
);
695 Dst
= LLVMBuildCatchSwitch(Builder
, ParentPad
, UnwindBB
, NumHandlers
, Name
);
696 if (NumHandlers
> 0) {
697 LLVMBasicBlockRef
*Handlers
= static_cast<LLVMBasicBlockRef
*>(
698 safe_malloc(NumHandlers
* sizeof(LLVMBasicBlockRef
)));
699 LLVMGetHandlers(Src
, Handlers
);
700 for (unsigned i
= 0; i
< NumHandlers
; i
++)
701 LLVMAddHandler(Dst
, DeclareBB(Handlers
[i
]));
706 case LLVMExtractValue
: {
707 LLVMValueRef Agg
= CloneValue(LLVMGetOperand(Src
, 0));
708 if (LLVMGetNumIndices(Src
) != 1)
709 report_fatal_error("Expected only one indice");
710 auto I
= LLVMGetIndices(Src
)[0];
711 Dst
= LLVMBuildExtractValue(Builder
, Agg
, I
, Name
);
714 case LLVMInsertValue
: {
715 LLVMValueRef Agg
= CloneValue(LLVMGetOperand(Src
, 0));
716 LLVMValueRef V
= CloneValue(LLVMGetOperand(Src
, 1));
717 if (LLVMGetNumIndices(Src
) != 1)
718 report_fatal_error("Expected only one indice");
719 auto I
= LLVMGetIndices(Src
)[0];
720 Dst
= LLVMBuildInsertValue(Builder
, Agg
, V
, I
, Name
);
727 if (Dst
== nullptr) {
728 fprintf(stderr
, "%d is not a supported opcode\n", Op
);
732 auto Ctx
= LLVMGetModuleContext(M
);
733 size_t NumMetadataEntries
;
735 LLVMInstructionGetAllMetadataOtherThanDebugLoc(Src
,
736 &NumMetadataEntries
);
737 for (unsigned i
= 0; i
< NumMetadataEntries
; ++i
) {
738 unsigned Kind
= LLVMValueMetadataEntriesGetKind(AllMetadata
, i
);
739 LLVMMetadataRef MD
= LLVMValueMetadataEntriesGetMetadata(AllMetadata
, i
);
740 LLVMSetMetadata(Dst
, Kind
, LLVMMetadataAsValue(Ctx
, MD
));
742 LLVMDisposeValueMetadataEntries(AllMetadata
);
743 LLVMSetInstDebugLocation(Builder
, Dst
);
745 check_value_kind(Dst
, LLVMInstructionValueKind
);
746 return VMap
[Src
] = Dst
;
749 LLVMBasicBlockRef
DeclareBB(LLVMBasicBlockRef Src
) {
750 // Check if this is something we already computed.
752 auto i
= BBMap
.find(Src
);
753 if (i
!= BBMap
.end()) {
758 LLVMValueRef V
= LLVMBasicBlockAsValue(Src
);
759 if (!LLVMValueIsBasicBlock(V
) || LLVMValueAsBasicBlock(V
) != Src
)
760 report_fatal_error("Basic block is not a basic block");
762 const char *Name
= LLVMGetBasicBlockName(Src
);
764 const char *VName
= LLVMGetValueName2(V
, &NameLen
);
766 report_fatal_error("Basic block name mismatch");
768 LLVMBasicBlockRef BB
= LLVMAppendBasicBlock(Fun
, Name
);
769 return BBMap
[Src
] = BB
;
772 LLVMBasicBlockRef
CloneBB(LLVMBasicBlockRef Src
) {
773 LLVMBasicBlockRef BB
= DeclareBB(Src
);
775 // Make sure ordering is correct.
776 LLVMBasicBlockRef Prev
= LLVMGetPreviousBasicBlock(Src
);
778 LLVMMoveBasicBlockAfter(BB
, DeclareBB(Prev
));
780 LLVMValueRef First
= LLVMGetFirstInstruction(Src
);
781 LLVMValueRef Last
= LLVMGetLastInstruction(Src
);
783 if (First
== nullptr) {
785 report_fatal_error("Has no first instruction, but last one");
789 auto Ctx
= LLVMGetModuleContext(M
);
790 LLVMBuilderRef Builder
= LLVMCreateBuilderInContext(Ctx
);
791 LLVMPositionBuilderAtEnd(Builder
, BB
);
793 LLVMValueRef Cur
= First
;
794 LLVMValueRef Next
= nullptr;
796 CloneInstruction(Cur
, Builder
);
797 Next
= LLVMGetNextInstruction(Cur
);
798 if (Next
== nullptr) {
800 report_fatal_error("Final instruction does not match Last");
804 LLVMValueRef Prev
= LLVMGetPreviousInstruction(Next
);
806 report_fatal_error("Next.Previous instruction is not Current");
811 LLVMDisposeBuilder(Builder
);
815 void CloneBBs(LLVMValueRef Src
) {
816 unsigned Count
= LLVMCountBasicBlocks(Src
);
820 LLVMBasicBlockRef First
= LLVMGetFirstBasicBlock(Src
);
821 LLVMBasicBlockRef Last
= LLVMGetLastBasicBlock(Src
);
823 LLVMBasicBlockRef Cur
= First
;
824 LLVMBasicBlockRef Next
= nullptr;
828 Next
= LLVMGetNextBasicBlock(Cur
);
829 if (Next
== nullptr) {
831 report_fatal_error("Final basic block does not match Last");
835 LLVMBasicBlockRef Prev
= LLVMGetPreviousBasicBlock(Next
);
837 report_fatal_error("Next.Previous basic bloc is not Current");
843 report_fatal_error("Basic block count does not match iterration");
847 static void declare_symbols(LLVMModuleRef Src
, LLVMModuleRef M
) {
848 auto Ctx
= LLVMGetModuleContext(M
);
850 LLVMValueRef Begin
= LLVMGetFirstGlobal(Src
);
851 LLVMValueRef End
= LLVMGetLastGlobal(Src
);
853 LLVMValueRef Cur
= Begin
;
854 LLVMValueRef Next
= nullptr;
857 report_fatal_error("Range has an end but no beginning");
863 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
864 if (LLVMGetNamedGlobal(M
, Name
))
865 report_fatal_error("GlobalVariable already cloned");
866 LLVMAddGlobal(M
, LLVMGetElementType(TypeCloner(M
).Clone(Cur
)), Name
);
868 Next
= LLVMGetNextGlobal(Cur
);
869 if (Next
== nullptr) {
871 report_fatal_error("");
875 LLVMValueRef Prev
= LLVMGetPreviousGlobal(Next
);
877 report_fatal_error("Next.Previous global is not Current");
883 Begin
= LLVMGetFirstFunction(Src
);
884 End
= LLVMGetLastFunction(Src
);
887 report_fatal_error("Range has an end but no beginning");
895 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
896 if (LLVMGetNamedFunction(M
, Name
))
897 report_fatal_error("Function already cloned");
898 auto Ty
= LLVMGetElementType(TypeCloner(M
).Clone(Cur
));
899 auto F
= LLVMAddFunction(M
, Name
, Ty
);
902 for (int i
= LLVMAttributeFunctionIndex
, c
= LLVMCountParams(F
);
904 for (unsigned k
= 0, e
= LLVMGetLastEnumAttributeKind(); k
< e
; ++k
) {
905 if (auto SrcA
= LLVMGetEnumAttributeAtIndex(Cur
, i
, k
)) {
906 auto Val
= LLVMGetEnumAttributeValue(SrcA
);
907 auto DstA
= LLVMCreateEnumAttribute(Ctx
, k
, Val
);
908 LLVMAddAttributeAtIndex(F
, i
, DstA
);
913 Next
= LLVMGetNextFunction(Cur
);
914 if (Next
== nullptr) {
916 report_fatal_error("Last function does not match End");
920 LLVMValueRef Prev
= LLVMGetPreviousFunction(Next
);
922 report_fatal_error("Next.Previous function is not Current");
928 Begin
= LLVMGetFirstGlobalAlias(Src
);
929 End
= LLVMGetLastGlobalAlias(Src
);
932 report_fatal_error("Range has an end but no beginning");
940 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
941 if (LLVMGetNamedGlobalAlias(M
, Name
, NameLen
))
942 report_fatal_error("Global alias already cloned");
943 LLVMTypeRef CurType
= TypeCloner(M
).Clone(Cur
);
944 // FIXME: Allow NULL aliasee.
945 LLVMAddAlias(M
, CurType
, LLVMGetUndef(CurType
), Name
);
947 Next
= LLVMGetNextGlobalAlias(Cur
);
948 if (Next
== nullptr) {
950 report_fatal_error("");
954 LLVMValueRef Prev
= LLVMGetPreviousGlobalAlias(Next
);
956 report_fatal_error("Next.Previous global is not Current");
962 LLVMNamedMDNodeRef BeginMD
= LLVMGetFirstNamedMetadata(Src
);
963 LLVMNamedMDNodeRef EndMD
= LLVMGetLastNamedMetadata(Src
);
965 if (EndMD
!= nullptr)
966 report_fatal_error("Range has an end but no beginning");
970 LLVMNamedMDNodeRef CurMD
= BeginMD
;
971 LLVMNamedMDNodeRef NextMD
= nullptr;
974 const char *Name
= LLVMGetNamedMetadataName(CurMD
, &NameLen
);
975 if (LLVMGetNamedMetadata(M
, Name
, NameLen
))
976 report_fatal_error("Named Metadata Node already cloned");
977 LLVMGetOrInsertNamedMetadata(M
, Name
, NameLen
);
979 NextMD
= LLVMGetNextNamedMetadata(CurMD
);
980 if (NextMD
== nullptr) {
982 report_fatal_error("");
986 LLVMNamedMDNodeRef PrevMD
= LLVMGetPreviousNamedMetadata(NextMD
);
988 report_fatal_error("Next.Previous global is not Current");
994 static void clone_symbols(LLVMModuleRef Src
, LLVMModuleRef M
) {
995 LLVMValueRef Begin
= LLVMGetFirstGlobal(Src
);
996 LLVMValueRef End
= LLVMGetLastGlobal(Src
);
998 LLVMValueRef Cur
= Begin
;
999 LLVMValueRef Next
= nullptr;
1002 report_fatal_error("Range has an end but no beginning");
1008 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
1009 LLVMValueRef G
= LLVMGetNamedGlobal(M
, Name
);
1011 report_fatal_error("GlobalVariable must have been declared already");
1013 if (auto I
= LLVMGetInitializer(Cur
))
1014 LLVMSetInitializer(G
, clone_constant(I
, M
));
1016 size_t NumMetadataEntries
;
1017 auto *AllMetadata
= LLVMGlobalCopyAllMetadata(Cur
, &NumMetadataEntries
);
1018 for (unsigned i
= 0; i
< NumMetadataEntries
; ++i
) {
1019 unsigned Kind
= LLVMValueMetadataEntriesGetKind(AllMetadata
, i
);
1020 LLVMMetadataRef MD
= LLVMValueMetadataEntriesGetMetadata(AllMetadata
, i
);
1021 LLVMGlobalSetMetadata(G
, Kind
, MD
);
1023 LLVMDisposeValueMetadataEntries(AllMetadata
);
1025 LLVMSetGlobalConstant(G
, LLVMIsGlobalConstant(Cur
));
1026 LLVMSetThreadLocal(G
, LLVMIsThreadLocal(Cur
));
1027 LLVMSetExternallyInitialized(G
, LLVMIsExternallyInitialized(Cur
));
1028 LLVMSetLinkage(G
, LLVMGetLinkage(Cur
));
1029 LLVMSetSection(G
, LLVMGetSection(Cur
));
1030 LLVMSetVisibility(G
, LLVMGetVisibility(Cur
));
1031 LLVMSetUnnamedAddress(G
, LLVMGetUnnamedAddress(Cur
));
1032 LLVMSetAlignment(G
, LLVMGetAlignment(Cur
));
1034 Next
= LLVMGetNextGlobal(Cur
);
1035 if (Next
== nullptr) {
1037 report_fatal_error("");
1041 LLVMValueRef Prev
= LLVMGetPreviousGlobal(Next
);
1043 report_fatal_error("Next.Previous global is not Current");
1049 Begin
= LLVMGetFirstFunction(Src
);
1050 End
= LLVMGetLastFunction(Src
);
1053 report_fatal_error("Range has an end but no beginning");
1061 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
1062 LLVMValueRef Fun
= LLVMGetNamedFunction(M
, Name
);
1064 report_fatal_error("Function must have been declared already");
1066 if (LLVMHasPersonalityFn(Cur
)) {
1068 const char *FName
= LLVMGetValueName2(LLVMGetPersonalityFn(Cur
),
1070 LLVMValueRef P
= LLVMGetNamedFunction(M
, FName
);
1072 report_fatal_error("Could not find personality function");
1073 LLVMSetPersonalityFn(Fun
, P
);
1076 size_t NumMetadataEntries
;
1077 auto *AllMetadata
= LLVMGlobalCopyAllMetadata(Cur
, &NumMetadataEntries
);
1078 for (unsigned i
= 0; i
< NumMetadataEntries
; ++i
) {
1079 unsigned Kind
= LLVMValueMetadataEntriesGetKind(AllMetadata
, i
);
1080 LLVMMetadataRef MD
= LLVMValueMetadataEntriesGetMetadata(AllMetadata
, i
);
1081 LLVMGlobalSetMetadata(Fun
, Kind
, MD
);
1083 LLVMDisposeValueMetadataEntries(AllMetadata
);
1085 FunCloner
FC(Cur
, Fun
);
1088 Next
= LLVMGetNextFunction(Cur
);
1089 if (Next
== nullptr) {
1091 report_fatal_error("Last function does not match End");
1095 LLVMValueRef Prev
= LLVMGetPreviousFunction(Next
);
1097 report_fatal_error("Next.Previous function is not Current");
1103 Begin
= LLVMGetFirstGlobalAlias(Src
);
1104 End
= LLVMGetLastGlobalAlias(Src
);
1107 report_fatal_error("Range has an end but no beginning");
1115 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
1116 LLVMValueRef Alias
= LLVMGetNamedGlobalAlias(M
, Name
, NameLen
);
1118 report_fatal_error("Global alias must have been declared already");
1120 if (LLVMValueRef Aliasee
= LLVMAliasGetAliasee(Cur
)) {
1121 LLVMAliasSetAliasee(Alias
, clone_constant(Aliasee
, M
));
1124 LLVMSetLinkage(Alias
, LLVMGetLinkage(Cur
));
1125 LLVMSetUnnamedAddress(Alias
, LLVMGetUnnamedAddress(Cur
));
1127 Next
= LLVMGetNextGlobalAlias(Cur
);
1128 if (Next
== nullptr) {
1130 report_fatal_error("Last global alias does not match End");
1134 LLVMValueRef Prev
= LLVMGetPreviousGlobalAlias(Next
);
1136 report_fatal_error("Next.Previous global alias is not Current");
1142 LLVMNamedMDNodeRef BeginMD
= LLVMGetFirstNamedMetadata(Src
);
1143 LLVMNamedMDNodeRef EndMD
= LLVMGetLastNamedMetadata(Src
);
1145 if (EndMD
!= nullptr)
1146 report_fatal_error("Range has an end but no beginning");
1150 LLVMNamedMDNodeRef CurMD
= BeginMD
;
1151 LLVMNamedMDNodeRef NextMD
= nullptr;
1154 const char *Name
= LLVMGetNamedMetadataName(CurMD
, &NameLen
);
1155 LLVMNamedMDNodeRef NamedMD
= LLVMGetNamedMetadata(M
, Name
, NameLen
);
1157 report_fatal_error("Named MD Node must have been declared already");
1159 unsigned OperandCount
= LLVMGetNamedMetadataNumOperands(Src
, Name
);
1160 LLVMValueRef
*OperandBuf
= static_cast<LLVMValueRef
*>(
1161 safe_malloc(OperandCount
* sizeof(LLVMValueRef
)));
1162 LLVMGetNamedMetadataOperands(Src
, Name
, OperandBuf
);
1163 for (unsigned i
= 0, e
= OperandCount
; i
!= e
; ++i
) {
1164 LLVMAddNamedMetadataOperand(M
, Name
, OperandBuf
[i
]);
1168 NextMD
= LLVMGetNextNamedMetadata(CurMD
);
1169 if (NextMD
== nullptr) {
1171 report_fatal_error("Last Named MD Node does not match End");
1175 LLVMNamedMDNodeRef PrevMD
= LLVMGetPreviousNamedMetadata(NextMD
);
1176 if (PrevMD
!= CurMD
)
1177 report_fatal_error("Next.Previous Named MD Node is not Current");
1183 int llvm_echo(void) {
1184 LLVMEnablePrettyStackTrace();
1186 LLVMModuleRef Src
= llvm_load_module(false, true);
1187 size_t SourceFileLen
;
1188 const char *SourceFileName
= LLVMGetSourceFileName(Src
, &SourceFileLen
);
1189 size_t ModuleIdentLen
;
1190 const char *ModuleName
= LLVMGetModuleIdentifier(Src
, &ModuleIdentLen
);
1191 LLVMContextRef Ctx
= LLVMContextCreate();
1192 LLVMModuleRef M
= LLVMModuleCreateWithNameInContext(ModuleName
, Ctx
);
1194 LLVMSetSourceFileName(M
, SourceFileName
, SourceFileLen
);
1195 LLVMSetModuleIdentifier(M
, ModuleName
, ModuleIdentLen
);
1197 LLVMSetTarget(M
, LLVMGetTarget(Src
));
1198 LLVMSetModuleDataLayout(M
, LLVMGetModuleDataLayout(Src
));
1199 if (strcmp(LLVMGetDataLayoutStr(M
), LLVMGetDataLayoutStr(Src
)))
1200 report_fatal_error("Inconsistent DataLayout string representation");
1202 size_t ModuleInlineAsmLen
;
1203 const char *ModuleAsm
= LLVMGetModuleInlineAsm(Src
, &ModuleInlineAsmLen
);
1204 LLVMSetModuleInlineAsm2(M
, ModuleAsm
, ModuleInlineAsmLen
);
1206 declare_symbols(Src
, M
);
1207 clone_symbols(Src
, M
);
1208 char *Str
= LLVMPrintModuleToString(M
);
1211 LLVMDisposeMessage(Str
);
1212 LLVMDisposeModule(Src
);
1213 LLVMDisposeModule(M
);
1214 LLVMContextDispose(Ctx
);