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
);
244 LLVMValueRef Dst
= nullptr;
246 unsigned ID
= LLVMGetIntrinsicID(Cst
);
247 if (ID
> 0 && !LLVMIntrinsicIsOverloaded(ID
)) {
248 Dst
= LLVMGetIntrinsicDeclaration(M
, ID
, nullptr, 0);
250 // Try a normal function
251 Dst
= LLVMGetNamedFunction(M
, Name
);
256 report_fatal_error("Could not find function");
259 // Try global variable
260 if (LLVMIsAGlobalVariable(Cst
)) {
261 check_value_kind(Cst
, LLVMGlobalVariableValueKind
);
262 LLVMValueRef Dst
= LLVMGetNamedGlobal(M
, Name
);
265 report_fatal_error("Could not find variable");
269 if (LLVMIsAGlobalAlias(Cst
)) {
270 check_value_kind(Cst
, LLVMGlobalAliasValueKind
);
271 LLVMValueRef Dst
= LLVMGetNamedGlobalAlias(M
, Name
, NameLen
);
274 report_fatal_error("Could not find alias");
277 fprintf(stderr
, "Could not find @%s\n", Name
);
281 // Try integer literal
282 if (LLVMIsAConstantInt(Cst
)) {
283 check_value_kind(Cst
, LLVMConstantIntValueKind
);
284 return LLVMConstInt(TypeCloner(M
).Clone(Cst
),
285 LLVMConstIntGetZExtValue(Cst
), false);
288 // Try zeroinitializer
289 if (LLVMIsAConstantAggregateZero(Cst
)) {
290 check_value_kind(Cst
, LLVMConstantAggregateZeroValueKind
);
291 return LLVMConstNull(TypeCloner(M
).Clone(Cst
));
294 // Try constant array
295 if (LLVMIsAConstantArray(Cst
)) {
296 check_value_kind(Cst
, LLVMConstantArrayValueKind
);
297 LLVMTypeRef Ty
= TypeCloner(M
).Clone(Cst
);
298 unsigned EltCount
= LLVMGetArrayLength(Ty
);
299 SmallVector
<LLVMValueRef
, 8> Elts
;
300 for (unsigned i
= 0; i
< EltCount
; i
++)
301 Elts
.push_back(clone_constant(LLVMGetOperand(Cst
, i
), M
));
302 return LLVMConstArray(LLVMGetElementType(Ty
), Elts
.data(), EltCount
);
305 // Try contant data array
306 if (LLVMIsAConstantDataArray(Cst
)) {
307 check_value_kind(Cst
, LLVMConstantDataArrayValueKind
);
308 LLVMTypeRef Ty
= TypeCloner(M
).Clone(Cst
);
309 unsigned EltCount
= LLVMGetArrayLength(Ty
);
310 SmallVector
<LLVMValueRef
, 8> Elts
;
311 for (unsigned i
= 0; i
< EltCount
; i
++)
312 Elts
.push_back(clone_constant(LLVMGetElementAsConstant(Cst
, i
), M
));
313 return LLVMConstArray(LLVMGetElementType(Ty
), Elts
.data(), EltCount
);
316 // Try constant struct
317 if (LLVMIsAConstantStruct(Cst
)) {
318 check_value_kind(Cst
, LLVMConstantStructValueKind
);
319 LLVMTypeRef Ty
= TypeCloner(M
).Clone(Cst
);
320 unsigned EltCount
= LLVMCountStructElementTypes(Ty
);
321 SmallVector
<LLVMValueRef
, 8> Elts
;
322 for (unsigned i
= 0; i
< EltCount
; i
++)
323 Elts
.push_back(clone_constant(LLVMGetOperand(Cst
, i
), M
));
324 if (LLVMGetStructName(Ty
))
325 return LLVMConstNamedStruct(Ty
, Elts
.data(), EltCount
);
326 return LLVMConstStructInContext(LLVMGetModuleContext(M
), Elts
.data(),
327 EltCount
, LLVMIsPackedStruct(Ty
));
331 if (LLVMIsUndef(Cst
)) {
332 check_value_kind(Cst
, LLVMUndefValueValueKind
);
333 return LLVMGetUndef(TypeCloner(M
).Clone(Cst
));
337 if (LLVMIsNull(Cst
)) {
338 check_value_kind(Cst
, LLVMConstantTokenNoneValueKind
);
339 LLVMTypeRef Ty
= TypeCloner(M
).Clone(Cst
);
340 return LLVMConstNull(Ty
);
344 if (LLVMIsAConstantFP(Cst
)) {
345 check_value_kind(Cst
, LLVMConstantFPValueKind
);
346 report_fatal_error("ConstantFP is not supported");
349 // This kind of constant is not supported
350 if (!LLVMIsAConstantExpr(Cst
))
351 report_fatal_error("Expected a constant expression");
353 // At this point, it must be a constant expression
354 check_value_kind(Cst
, LLVMConstantExprValueKind
);
356 LLVMOpcode Op
= LLVMGetConstOpcode(Cst
);
359 return LLVMConstBitCast(clone_constant(LLVMGetOperand(Cst
, 0), M
),
360 TypeCloner(M
).Clone(Cst
));
362 fprintf(stderr
, "%d is not a supported opcode\n", Op
);
374 FunCloner(LLVMValueRef Src
, LLVMValueRef Dst
): Fun(Dst
),
375 M(LLVMGetGlobalParent(Fun
)), VMap(clone_params(Src
, Dst
)) {}
377 LLVMTypeRef
CloneType(LLVMTypeRef Src
) {
378 return TypeCloner(M
).Clone(Src
);
381 LLVMTypeRef
CloneType(LLVMValueRef Src
) {
382 return TypeCloner(M
).Clone(Src
);
385 // Try to clone everything in the llvm::Value hierarchy.
386 LLVMValueRef
CloneValue(LLVMValueRef Src
) {
387 // First, the value may be constant.
388 if (LLVMIsAConstant(Src
))
389 return clone_constant(Src
, M
);
391 // Function argument should always be in the map already.
392 auto i
= VMap
.find(Src
);
396 if (!LLVMIsAInstruction(Src
))
397 report_fatal_error("Expected an instruction");
399 auto Ctx
= LLVMGetModuleContext(M
);
400 auto Builder
= LLVMCreateBuilderInContext(Ctx
);
401 auto BB
= DeclareBB(LLVMGetInstructionParent(Src
));
402 LLVMPositionBuilderAtEnd(Builder
, BB
);
403 auto Dst
= CloneInstruction(Src
, Builder
);
404 LLVMDisposeBuilder(Builder
);
408 void CloneAttrs(LLVMValueRef Src
, LLVMValueRef Dst
) {
409 auto Ctx
= LLVMGetModuleContext(M
);
410 int ArgCount
= LLVMGetNumArgOperands(Src
);
411 for (int i
= LLVMAttributeReturnIndex
; i
<= ArgCount
; i
++) {
412 for (unsigned k
= 0, e
= LLVMGetLastEnumAttributeKind(); k
< e
; ++k
) {
413 if (auto SrcA
= LLVMGetCallSiteEnumAttribute(Src
, i
, k
)) {
414 auto Val
= LLVMGetEnumAttributeValue(SrcA
);
415 auto A
= LLVMCreateEnumAttribute(Ctx
, k
, Val
);
416 LLVMAddCallSiteAttribute(Dst
, i
, A
);
422 LLVMValueRef
CloneInstruction(LLVMValueRef Src
, LLVMBuilderRef Builder
) {
423 check_value_kind(Src
, LLVMInstructionValueKind
);
424 if (!LLVMIsAInstruction(Src
))
425 report_fatal_error("Expected an instruction");
428 const char *Name
= LLVMGetValueName2(Src
, &NameLen
);
430 // Check if this is something we already computed.
432 auto i
= VMap
.find(Src
);
433 if (i
!= VMap
.end()) {
434 // If we have a hit, it means we already generated the instruction
435 // as a dependancy to somethign else. We need to make sure
436 // it is ordered properly.
438 LLVMInstructionRemoveFromParent(I
);
439 LLVMInsertIntoBuilderWithName(Builder
, I
, Name
);
444 // We tried everything, it must be an instruction
445 // that hasn't been generated already.
446 LLVMValueRef Dst
= nullptr;
448 LLVMOpcode Op
= LLVMGetInstructionOpcode(Src
);
451 int OpCount
= LLVMGetNumOperands(Src
);
453 Dst
= LLVMBuildRetVoid(Builder
);
455 Dst
= LLVMBuildRet(Builder
, CloneValue(LLVMGetOperand(Src
, 0)));
459 if (!LLVMIsConditional(Src
)) {
460 LLVMValueRef SrcOp
= LLVMGetOperand(Src
, 0);
461 LLVMBasicBlockRef SrcBB
= LLVMValueAsBasicBlock(SrcOp
);
462 Dst
= LLVMBuildBr(Builder
, DeclareBB(SrcBB
));
466 LLVMValueRef Cond
= LLVMGetCondition(Src
);
467 LLVMValueRef Else
= LLVMGetOperand(Src
, 1);
468 LLVMBasicBlockRef ElseBB
= DeclareBB(LLVMValueAsBasicBlock(Else
));
469 LLVMValueRef Then
= LLVMGetOperand(Src
, 2);
470 LLVMBasicBlockRef ThenBB
= DeclareBB(LLVMValueAsBasicBlock(Then
));
471 Dst
= LLVMBuildCondBr(Builder
, CloneValue(Cond
), ThenBB
, ElseBB
);
478 SmallVector
<LLVMValueRef
, 8> Args
;
479 int ArgCount
= LLVMGetNumArgOperands(Src
);
480 for (int i
= 0; i
< ArgCount
; i
++)
481 Args
.push_back(CloneValue(LLVMGetOperand(Src
, i
)));
482 LLVMValueRef Fn
= CloneValue(LLVMGetCalledValue(Src
));
483 LLVMBasicBlockRef Then
= DeclareBB(LLVMGetNormalDest(Src
));
484 LLVMBasicBlockRef Unwind
= DeclareBB(LLVMGetUnwindDest(Src
));
485 Dst
= LLVMBuildInvoke(Builder
, Fn
, Args
.data(), ArgCount
,
487 CloneAttrs(Src
, Dst
);
490 case LLVMUnreachable
:
491 Dst
= LLVMBuildUnreachable(Builder
);
494 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
495 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
496 Dst
= LLVMBuildAdd(Builder
, LHS
, RHS
, Name
);
500 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
501 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
502 Dst
= LLVMBuildSub(Builder
, LHS
, RHS
, Name
);
506 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
507 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
508 Dst
= LLVMBuildMul(Builder
, LHS
, RHS
, Name
);
512 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
513 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
514 Dst
= LLVMBuildUDiv(Builder
, LHS
, RHS
, Name
);
518 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
519 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
520 Dst
= LLVMBuildSDiv(Builder
, LHS
, RHS
, Name
);
524 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
525 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
526 Dst
= LLVMBuildURem(Builder
, LHS
, RHS
, Name
);
530 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
531 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
532 Dst
= LLVMBuildSRem(Builder
, LHS
, RHS
, Name
);
536 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
537 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
538 Dst
= LLVMBuildShl(Builder
, LHS
, RHS
, Name
);
542 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
543 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
544 Dst
= LLVMBuildLShr(Builder
, LHS
, RHS
, Name
);
548 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
549 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
550 Dst
= LLVMBuildAShr(Builder
, LHS
, RHS
, Name
);
554 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
555 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
556 Dst
= LLVMBuildAnd(Builder
, LHS
, RHS
, Name
);
560 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
561 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
562 Dst
= LLVMBuildOr(Builder
, LHS
, RHS
, Name
);
566 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
567 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
568 Dst
= LLVMBuildXor(Builder
, LHS
, RHS
, Name
);
572 LLVMTypeRef Ty
= CloneType(LLVMGetAllocatedType(Src
));
573 Dst
= LLVMBuildAlloca(Builder
, Ty
, Name
);
577 LLVMValueRef Ptr
= CloneValue(LLVMGetOperand(Src
, 0));
578 Dst
= LLVMBuildLoad(Builder
, Ptr
, Name
);
579 LLVMSetAlignment(Dst
, LLVMGetAlignment(Src
));
583 LLVMValueRef Val
= CloneValue(LLVMGetOperand(Src
, 0));
584 LLVMValueRef Ptr
= CloneValue(LLVMGetOperand(Src
, 1));
585 Dst
= LLVMBuildStore(Builder
, Val
, Ptr
);
586 LLVMSetAlignment(Dst
, LLVMGetAlignment(Src
));
589 case LLVMGetElementPtr
: {
590 LLVMValueRef Ptr
= CloneValue(LLVMGetOperand(Src
, 0));
591 SmallVector
<LLVMValueRef
, 8> Idx
;
592 int NumIdx
= LLVMGetNumIndices(Src
);
593 for (int i
= 1; i
<= NumIdx
; i
++)
594 Idx
.push_back(CloneValue(LLVMGetOperand(Src
, i
)));
595 if (LLVMIsInBounds(Src
))
596 Dst
= LLVMBuildInBoundsGEP(Builder
, Ptr
, Idx
.data(), NumIdx
, Name
);
598 Dst
= LLVMBuildGEP(Builder
, Ptr
, Idx
.data(), NumIdx
, Name
);
601 case LLVMAtomicCmpXchg
: {
602 LLVMValueRef Ptr
= CloneValue(LLVMGetOperand(Src
, 0));
603 LLVMValueRef Cmp
= CloneValue(LLVMGetOperand(Src
, 1));
604 LLVMValueRef New
= CloneValue(LLVMGetOperand(Src
, 2));
605 LLVMAtomicOrdering Succ
= LLVMGetCmpXchgSuccessOrdering(Src
);
606 LLVMAtomicOrdering Fail
= LLVMGetCmpXchgFailureOrdering(Src
);
607 LLVMBool SingleThread
= LLVMIsAtomicSingleThread(Src
);
609 Dst
= LLVMBuildAtomicCmpXchg(Builder
, Ptr
, Cmp
, New
, Succ
, Fail
,
613 LLVMValueRef V
= CloneValue(LLVMGetOperand(Src
, 0));
614 Dst
= LLVMBuildBitCast(Builder
, V
, CloneType(Src
), Name
);
618 LLVMIntPredicate Pred
= LLVMGetICmpPredicate(Src
);
619 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
620 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
621 Dst
= LLVMBuildICmp(Builder
, Pred
, LHS
, RHS
, Name
);
625 // We need to aggressively set things here because of loops.
626 VMap
[Src
] = Dst
= LLVMBuildPhi(Builder
, CloneType(Src
), Name
);
628 SmallVector
<LLVMValueRef
, 8> Values
;
629 SmallVector
<LLVMBasicBlockRef
, 8> Blocks
;
631 unsigned IncomingCount
= LLVMCountIncoming(Src
);
632 for (unsigned i
= 0; i
< IncomingCount
; ++i
) {
633 Blocks
.push_back(DeclareBB(LLVMGetIncomingBlock(Src
, i
)));
634 Values
.push_back(CloneValue(LLVMGetIncomingValue(Src
, i
)));
637 LLVMAddIncoming(Dst
, Values
.data(), Blocks
.data(), IncomingCount
);
641 SmallVector
<LLVMValueRef
, 8> Args
;
642 int ArgCount
= LLVMGetNumArgOperands(Src
);
643 for (int i
= 0; i
< ArgCount
; i
++)
644 Args
.push_back(CloneValue(LLVMGetOperand(Src
, i
)));
645 LLVMValueRef Fn
= CloneValue(LLVMGetCalledValue(Src
));
646 Dst
= LLVMBuildCall(Builder
, Fn
, Args
.data(), ArgCount
, Name
);
647 LLVMSetTailCall(Dst
, LLVMIsTailCall(Src
));
648 CloneAttrs(Src
, Dst
);
652 Dst
= LLVMBuildResume(Builder
, CloneValue(LLVMGetOperand(Src
, 0)));
655 case LLVMLandingPad
: {
656 // The landing pad API is a bit screwed up for historical reasons.
657 Dst
= LLVMBuildLandingPad(Builder
, CloneType(Src
), nullptr, 0, Name
);
658 unsigned NumClauses
= LLVMGetNumClauses(Src
);
659 for (unsigned i
= 0; i
< NumClauses
; ++i
)
660 LLVMAddClause(Dst
, CloneValue(LLVMGetClause(Src
, i
)));
661 LLVMSetCleanup(Dst
, LLVMIsCleanup(Src
));
664 case LLVMCleanupRet
: {
665 LLVMValueRef CatchPad
= CloneValue(LLVMGetOperand(Src
, 0));
666 LLVMBasicBlockRef Unwind
= nullptr;
667 if (LLVMBasicBlockRef UDest
= LLVMGetUnwindDest(Src
))
668 Unwind
= DeclareBB(UDest
);
669 Dst
= LLVMBuildCleanupRet(Builder
, CatchPad
, Unwind
);
673 LLVMValueRef CatchPad
= CloneValue(LLVMGetOperand(Src
, 0));
674 LLVMBasicBlockRef SuccBB
= DeclareBB(LLVMGetSuccessor(Src
, 0));
675 Dst
= LLVMBuildCatchRet(Builder
, CatchPad
, SuccBB
);
679 LLVMValueRef ParentPad
= CloneValue(LLVMGetParentCatchSwitch(Src
));
680 SmallVector
<LLVMValueRef
, 8> Args
;
681 int ArgCount
= LLVMGetNumArgOperands(Src
);
682 for (int i
= 0; i
< ArgCount
; i
++)
683 Args
.push_back(CloneValue(LLVMGetOperand(Src
, i
)));
684 Dst
= LLVMBuildCatchPad(Builder
, ParentPad
,
685 Args
.data(), ArgCount
, Name
);
688 case LLVMCleanupPad
: {
689 LLVMValueRef ParentPad
= CloneValue(LLVMGetOperand(Src
, 0));
690 SmallVector
<LLVMValueRef
, 8> Args
;
691 int ArgCount
= LLVMGetNumArgOperands(Src
);
692 for (int i
= 0; i
< ArgCount
; i
++)
693 Args
.push_back(CloneValue(LLVMGetArgOperand(Src
, i
)));
694 Dst
= LLVMBuildCleanupPad(Builder
, ParentPad
,
695 Args
.data(), ArgCount
, Name
);
698 case LLVMCatchSwitch
: {
699 LLVMValueRef ParentPad
= CloneValue(LLVMGetOperand(Src
, 0));
700 LLVMBasicBlockRef UnwindBB
= nullptr;
701 if (LLVMBasicBlockRef UDest
= LLVMGetUnwindDest(Src
)) {
702 UnwindBB
= DeclareBB(UDest
);
704 unsigned NumHandlers
= LLVMGetNumHandlers(Src
);
705 Dst
= LLVMBuildCatchSwitch(Builder
, ParentPad
, UnwindBB
, NumHandlers
, Name
);
706 if (NumHandlers
> 0) {
707 LLVMBasicBlockRef
*Handlers
= static_cast<LLVMBasicBlockRef
*>(
708 safe_malloc(NumHandlers
* sizeof(LLVMBasicBlockRef
)));
709 LLVMGetHandlers(Src
, Handlers
);
710 for (unsigned i
= 0; i
< NumHandlers
; i
++)
711 LLVMAddHandler(Dst
, DeclareBB(Handlers
[i
]));
716 case LLVMExtractValue
: {
717 LLVMValueRef Agg
= CloneValue(LLVMGetOperand(Src
, 0));
718 if (LLVMGetNumIndices(Src
) != 1)
719 report_fatal_error("Expected only one indice");
720 auto I
= LLVMGetIndices(Src
)[0];
721 Dst
= LLVMBuildExtractValue(Builder
, Agg
, I
, Name
);
724 case LLVMInsertValue
: {
725 LLVMValueRef Agg
= CloneValue(LLVMGetOperand(Src
, 0));
726 LLVMValueRef V
= CloneValue(LLVMGetOperand(Src
, 1));
727 if (LLVMGetNumIndices(Src
) != 1)
728 report_fatal_error("Expected only one indice");
729 auto I
= LLVMGetIndices(Src
)[0];
730 Dst
= LLVMBuildInsertValue(Builder
, Agg
, V
, I
, Name
);
737 if (Dst
== nullptr) {
738 fprintf(stderr
, "%d is not a supported opcode\n", Op
);
742 auto Ctx
= LLVMGetModuleContext(M
);
743 size_t NumMetadataEntries
;
745 LLVMInstructionGetAllMetadataOtherThanDebugLoc(Src
,
746 &NumMetadataEntries
);
747 for (unsigned i
= 0; i
< NumMetadataEntries
; ++i
) {
748 unsigned Kind
= LLVMValueMetadataEntriesGetKind(AllMetadata
, i
);
749 LLVMMetadataRef MD
= LLVMValueMetadataEntriesGetMetadata(AllMetadata
, i
);
750 LLVMSetMetadata(Dst
, Kind
, LLVMMetadataAsValue(Ctx
, MD
));
752 LLVMDisposeValueMetadataEntries(AllMetadata
);
753 LLVMSetInstDebugLocation(Builder
, Dst
);
755 check_value_kind(Dst
, LLVMInstructionValueKind
);
756 return VMap
[Src
] = Dst
;
759 LLVMBasicBlockRef
DeclareBB(LLVMBasicBlockRef Src
) {
760 // Check if this is something we already computed.
762 auto i
= BBMap
.find(Src
);
763 if (i
!= BBMap
.end()) {
768 LLVMValueRef V
= LLVMBasicBlockAsValue(Src
);
769 if (!LLVMValueIsBasicBlock(V
) || LLVMValueAsBasicBlock(V
) != Src
)
770 report_fatal_error("Basic block is not a basic block");
772 const char *Name
= LLVMGetBasicBlockName(Src
);
774 const char *VName
= LLVMGetValueName2(V
, &NameLen
);
776 report_fatal_error("Basic block name mismatch");
778 LLVMBasicBlockRef BB
= LLVMAppendBasicBlock(Fun
, Name
);
779 return BBMap
[Src
] = BB
;
782 LLVMBasicBlockRef
CloneBB(LLVMBasicBlockRef Src
) {
783 LLVMBasicBlockRef BB
= DeclareBB(Src
);
785 // Make sure ordering is correct.
786 LLVMBasicBlockRef Prev
= LLVMGetPreviousBasicBlock(Src
);
788 LLVMMoveBasicBlockAfter(BB
, DeclareBB(Prev
));
790 LLVMValueRef First
= LLVMGetFirstInstruction(Src
);
791 LLVMValueRef Last
= LLVMGetLastInstruction(Src
);
793 if (First
== nullptr) {
795 report_fatal_error("Has no first instruction, but last one");
799 auto Ctx
= LLVMGetModuleContext(M
);
800 LLVMBuilderRef Builder
= LLVMCreateBuilderInContext(Ctx
);
801 LLVMPositionBuilderAtEnd(Builder
, BB
);
803 LLVMValueRef Cur
= First
;
804 LLVMValueRef Next
= nullptr;
806 CloneInstruction(Cur
, Builder
);
807 Next
= LLVMGetNextInstruction(Cur
);
808 if (Next
== nullptr) {
810 report_fatal_error("Final instruction does not match Last");
814 LLVMValueRef Prev
= LLVMGetPreviousInstruction(Next
);
816 report_fatal_error("Next.Previous instruction is not Current");
821 LLVMDisposeBuilder(Builder
);
825 void CloneBBs(LLVMValueRef Src
) {
826 unsigned Count
= LLVMCountBasicBlocks(Src
);
830 LLVMBasicBlockRef First
= LLVMGetFirstBasicBlock(Src
);
831 LLVMBasicBlockRef Last
= LLVMGetLastBasicBlock(Src
);
833 LLVMBasicBlockRef Cur
= First
;
834 LLVMBasicBlockRef Next
= nullptr;
838 Next
= LLVMGetNextBasicBlock(Cur
);
839 if (Next
== nullptr) {
841 report_fatal_error("Final basic block does not match Last");
845 LLVMBasicBlockRef Prev
= LLVMGetPreviousBasicBlock(Next
);
847 report_fatal_error("Next.Previous basic bloc is not Current");
853 report_fatal_error("Basic block count does not match iterration");
857 static void declare_symbols(LLVMModuleRef Src
, LLVMModuleRef M
) {
858 auto Ctx
= LLVMGetModuleContext(M
);
860 LLVMValueRef Begin
= LLVMGetFirstGlobal(Src
);
861 LLVMValueRef End
= LLVMGetLastGlobal(Src
);
863 LLVMValueRef Cur
= Begin
;
864 LLVMValueRef Next
= nullptr;
867 report_fatal_error("Range has an end but no beginning");
873 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
874 if (LLVMGetNamedGlobal(M
, Name
))
875 report_fatal_error("GlobalVariable already cloned");
876 LLVMAddGlobal(M
, LLVMGetElementType(TypeCloner(M
).Clone(Cur
)), Name
);
878 Next
= LLVMGetNextGlobal(Cur
);
879 if (Next
== nullptr) {
881 report_fatal_error("");
885 LLVMValueRef Prev
= LLVMGetPreviousGlobal(Next
);
887 report_fatal_error("Next.Previous global is not Current");
893 Begin
= LLVMGetFirstFunction(Src
);
894 End
= LLVMGetLastFunction(Src
);
897 report_fatal_error("Range has an end but no beginning");
905 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
906 if (LLVMGetNamedFunction(M
, Name
))
907 report_fatal_error("Function already cloned");
908 auto Ty
= LLVMGetElementType(TypeCloner(M
).Clone(Cur
));
909 auto F
= LLVMAddFunction(M
, Name
, Ty
);
912 for (int i
= LLVMAttributeFunctionIndex
, c
= LLVMCountParams(F
);
914 for (unsigned k
= 0, e
= LLVMGetLastEnumAttributeKind(); k
< e
; ++k
) {
915 if (auto SrcA
= LLVMGetEnumAttributeAtIndex(Cur
, i
, k
)) {
916 auto Val
= LLVMGetEnumAttributeValue(SrcA
);
917 auto DstA
= LLVMCreateEnumAttribute(Ctx
, k
, Val
);
918 LLVMAddAttributeAtIndex(F
, i
, DstA
);
923 Next
= LLVMGetNextFunction(Cur
);
924 if (Next
== nullptr) {
926 report_fatal_error("Last function does not match End");
930 LLVMValueRef Prev
= LLVMGetPreviousFunction(Next
);
932 report_fatal_error("Next.Previous function is not Current");
938 Begin
= LLVMGetFirstGlobalAlias(Src
);
939 End
= LLVMGetLastGlobalAlias(Src
);
942 report_fatal_error("Range has an end but no beginning");
950 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
951 if (LLVMGetNamedGlobalAlias(M
, Name
, NameLen
))
952 report_fatal_error("Global alias already cloned");
953 LLVMTypeRef CurType
= TypeCloner(M
).Clone(Cur
);
954 // FIXME: Allow NULL aliasee.
955 LLVMAddAlias(M
, CurType
, LLVMGetUndef(CurType
), Name
);
957 Next
= LLVMGetNextGlobalAlias(Cur
);
958 if (Next
== nullptr) {
960 report_fatal_error("");
964 LLVMValueRef Prev
= LLVMGetPreviousGlobalAlias(Next
);
966 report_fatal_error("Next.Previous global is not Current");
972 LLVMNamedMDNodeRef BeginMD
= LLVMGetFirstNamedMetadata(Src
);
973 LLVMNamedMDNodeRef EndMD
= LLVMGetLastNamedMetadata(Src
);
975 if (EndMD
!= nullptr)
976 report_fatal_error("Range has an end but no beginning");
980 LLVMNamedMDNodeRef CurMD
= BeginMD
;
981 LLVMNamedMDNodeRef NextMD
= nullptr;
984 const char *Name
= LLVMGetNamedMetadataName(CurMD
, &NameLen
);
985 if (LLVMGetNamedMetadata(M
, Name
, NameLen
))
986 report_fatal_error("Named Metadata Node already cloned");
987 LLVMGetOrInsertNamedMetadata(M
, Name
, NameLen
);
989 NextMD
= LLVMGetNextNamedMetadata(CurMD
);
990 if (NextMD
== nullptr) {
992 report_fatal_error("");
996 LLVMNamedMDNodeRef PrevMD
= LLVMGetPreviousNamedMetadata(NextMD
);
998 report_fatal_error("Next.Previous global is not Current");
1004 static void clone_symbols(LLVMModuleRef Src
, LLVMModuleRef M
) {
1005 LLVMValueRef Begin
= LLVMGetFirstGlobal(Src
);
1006 LLVMValueRef End
= LLVMGetLastGlobal(Src
);
1008 LLVMValueRef Cur
= Begin
;
1009 LLVMValueRef Next
= nullptr;
1012 report_fatal_error("Range has an end but no beginning");
1018 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
1019 LLVMValueRef G
= LLVMGetNamedGlobal(M
, Name
);
1021 report_fatal_error("GlobalVariable must have been declared already");
1023 if (auto I
= LLVMGetInitializer(Cur
))
1024 LLVMSetInitializer(G
, clone_constant(I
, M
));
1026 size_t NumMetadataEntries
;
1027 auto *AllMetadata
= LLVMGlobalCopyAllMetadata(Cur
, &NumMetadataEntries
);
1028 for (unsigned i
= 0; i
< NumMetadataEntries
; ++i
) {
1029 unsigned Kind
= LLVMValueMetadataEntriesGetKind(AllMetadata
, i
);
1030 LLVMMetadataRef MD
= LLVMValueMetadataEntriesGetMetadata(AllMetadata
, i
);
1031 LLVMGlobalSetMetadata(G
, Kind
, MD
);
1033 LLVMDisposeValueMetadataEntries(AllMetadata
);
1035 LLVMSetGlobalConstant(G
, LLVMIsGlobalConstant(Cur
));
1036 LLVMSetThreadLocal(G
, LLVMIsThreadLocal(Cur
));
1037 LLVMSetExternallyInitialized(G
, LLVMIsExternallyInitialized(Cur
));
1038 LLVMSetLinkage(G
, LLVMGetLinkage(Cur
));
1039 LLVMSetSection(G
, LLVMGetSection(Cur
));
1040 LLVMSetVisibility(G
, LLVMGetVisibility(Cur
));
1041 LLVMSetUnnamedAddress(G
, LLVMGetUnnamedAddress(Cur
));
1042 LLVMSetAlignment(G
, LLVMGetAlignment(Cur
));
1044 Next
= LLVMGetNextGlobal(Cur
);
1045 if (Next
== nullptr) {
1047 report_fatal_error("");
1051 LLVMValueRef Prev
= LLVMGetPreviousGlobal(Next
);
1053 report_fatal_error("Next.Previous global is not Current");
1059 Begin
= LLVMGetFirstFunction(Src
);
1060 End
= LLVMGetLastFunction(Src
);
1063 report_fatal_error("Range has an end but no beginning");
1071 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
1072 LLVMValueRef Fun
= LLVMGetNamedFunction(M
, Name
);
1074 report_fatal_error("Function must have been declared already");
1076 if (LLVMHasPersonalityFn(Cur
)) {
1078 const char *FName
= LLVMGetValueName2(LLVMGetPersonalityFn(Cur
),
1080 LLVMValueRef P
= LLVMGetNamedFunction(M
, FName
);
1082 report_fatal_error("Could not find personality function");
1083 LLVMSetPersonalityFn(Fun
, P
);
1086 size_t NumMetadataEntries
;
1087 auto *AllMetadata
= LLVMGlobalCopyAllMetadata(Cur
, &NumMetadataEntries
);
1088 for (unsigned i
= 0; i
< NumMetadataEntries
; ++i
) {
1089 unsigned Kind
= LLVMValueMetadataEntriesGetKind(AllMetadata
, i
);
1090 LLVMMetadataRef MD
= LLVMValueMetadataEntriesGetMetadata(AllMetadata
, i
);
1091 LLVMGlobalSetMetadata(Fun
, Kind
, MD
);
1093 LLVMDisposeValueMetadataEntries(AllMetadata
);
1095 FunCloner
FC(Cur
, Fun
);
1098 Next
= LLVMGetNextFunction(Cur
);
1099 if (Next
== nullptr) {
1101 report_fatal_error("Last function does not match End");
1105 LLVMValueRef Prev
= LLVMGetPreviousFunction(Next
);
1107 report_fatal_error("Next.Previous function is not Current");
1113 Begin
= LLVMGetFirstGlobalAlias(Src
);
1114 End
= LLVMGetLastGlobalAlias(Src
);
1117 report_fatal_error("Range has an end but no beginning");
1125 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
1126 LLVMValueRef Alias
= LLVMGetNamedGlobalAlias(M
, Name
, NameLen
);
1128 report_fatal_error("Global alias must have been declared already");
1130 if (LLVMValueRef Aliasee
= LLVMAliasGetAliasee(Cur
)) {
1131 LLVMAliasSetAliasee(Alias
, clone_constant(Aliasee
, M
));
1134 LLVMSetLinkage(Alias
, LLVMGetLinkage(Cur
));
1135 LLVMSetUnnamedAddress(Alias
, LLVMGetUnnamedAddress(Cur
));
1137 Next
= LLVMGetNextGlobalAlias(Cur
);
1138 if (Next
== nullptr) {
1140 report_fatal_error("Last global alias does not match End");
1144 LLVMValueRef Prev
= LLVMGetPreviousGlobalAlias(Next
);
1146 report_fatal_error("Next.Previous global alias is not Current");
1152 LLVMNamedMDNodeRef BeginMD
= LLVMGetFirstNamedMetadata(Src
);
1153 LLVMNamedMDNodeRef EndMD
= LLVMGetLastNamedMetadata(Src
);
1155 if (EndMD
!= nullptr)
1156 report_fatal_error("Range has an end but no beginning");
1160 LLVMNamedMDNodeRef CurMD
= BeginMD
;
1161 LLVMNamedMDNodeRef NextMD
= nullptr;
1164 const char *Name
= LLVMGetNamedMetadataName(CurMD
, &NameLen
);
1165 LLVMNamedMDNodeRef NamedMD
= LLVMGetNamedMetadata(M
, Name
, NameLen
);
1167 report_fatal_error("Named MD Node must have been declared already");
1169 unsigned OperandCount
= LLVMGetNamedMetadataNumOperands(Src
, Name
);
1170 LLVMValueRef
*OperandBuf
= static_cast<LLVMValueRef
*>(
1171 safe_malloc(OperandCount
* sizeof(LLVMValueRef
)));
1172 LLVMGetNamedMetadataOperands(Src
, Name
, OperandBuf
);
1173 for (unsigned i
= 0, e
= OperandCount
; i
!= e
; ++i
) {
1174 LLVMAddNamedMetadataOperand(M
, Name
, OperandBuf
[i
]);
1178 NextMD
= LLVMGetNextNamedMetadata(CurMD
);
1179 if (NextMD
== nullptr) {
1181 report_fatal_error("Last Named MD Node does not match End");
1185 LLVMNamedMDNodeRef PrevMD
= LLVMGetPreviousNamedMetadata(NextMD
);
1186 if (PrevMD
!= CurMD
)
1187 report_fatal_error("Next.Previous Named MD Node is not Current");
1193 int llvm_echo(void) {
1194 LLVMEnablePrettyStackTrace();
1196 LLVMModuleRef Src
= llvm_load_module(false, true);
1197 size_t SourceFileLen
;
1198 const char *SourceFileName
= LLVMGetSourceFileName(Src
, &SourceFileLen
);
1199 size_t ModuleIdentLen
;
1200 const char *ModuleName
= LLVMGetModuleIdentifier(Src
, &ModuleIdentLen
);
1201 LLVMContextRef Ctx
= LLVMContextCreate();
1202 LLVMModuleRef M
= LLVMModuleCreateWithNameInContext(ModuleName
, Ctx
);
1204 LLVMSetSourceFileName(M
, SourceFileName
, SourceFileLen
);
1205 LLVMSetModuleIdentifier(M
, ModuleName
, ModuleIdentLen
);
1207 LLVMSetTarget(M
, LLVMGetTarget(Src
));
1208 LLVMSetModuleDataLayout(M
, LLVMGetModuleDataLayout(Src
));
1209 if (strcmp(LLVMGetDataLayoutStr(M
), LLVMGetDataLayoutStr(Src
)))
1210 report_fatal_error("Inconsistent DataLayout string representation");
1212 size_t ModuleInlineAsmLen
;
1213 const char *ModuleAsm
= LLVMGetModuleInlineAsm(Src
, &ModuleInlineAsmLen
);
1214 LLVMSetModuleInlineAsm2(M
, ModuleAsm
, ModuleInlineAsmLen
);
1216 declare_symbols(Src
, M
);
1217 clone_symbols(Src
, M
);
1218 char *Str
= LLVMPrintModuleToString(M
);
1221 LLVMDisposeMessage(Str
);
1222 LLVMDisposeModule(Src
);
1223 LLVMDisposeModule(M
);
1224 LLVMContextDispose(Ctx
);